Ajax从点击事件调用问题



查看下面的HTML代码:

<div class="user-avatar-wrapper"> 
<img class="profile-pic" src="/placeholder.png" alt="" />
<div class="upload-button"></div>
<input class="file-upload" type="file" accept="image/*"/>
</div>

现在我想触发文件上传,并在.upload-button点击时调用ajax。

这就是我在jQuery、中尝试的方式

$(document).on('click', '.upload-button', function(e) {
e.preventDefault();
//$(".file-upload").click();
$(this).next().trigger('click', function() {
var $data = { 'title': 'Title', 'file': 'myfile' };
$.ajax({
type: 'POST',
url: 'upload.php',
data: $data,
success: function(response) {     
},
error: function(response) {},
});
});
});

但是,这段代码对我不起作用。这意味着它没有发送ajax请求。

希望有人能帮我。

我认为您混淆了触发器和事件处理程序
当您单击div时,您应该触发对文件输入的单击,但不会在那里传递回调
您希望为文件输入设置一个更改处理程序,以便在使用change事件处理程序选择文件时发出ajax请求。

$(document).on('change', '.file-upload', function(e){
var data = new FormData();
data.append('title', 'Title');
data.append('file', this.files[0]);
$.ajax({
type: 'POST',
url: 'upload.php',
data: data,
processData: false,
contentType: false,
success: function(response) {     
},
error: function(response) {},
});
$(this).prev().html(`↑${this.files[0].name}`);
});
$(document).on('click', '.upload-button', function(e) {
$(this).next().click();
});
.upload-button{
cursor:pointer;
}
.file-upload{
opacity:0.01
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="user-avatar-wrapper"> 
<img class="profile-pic" src="/placeholder.png" alt="" />
<div class="upload-button">↑</div>
<input class="file-upload" type="file" accept="image/*"/>
</div>
<div class="user-avatar-wrapper"> 
<img class="profile-pic" src="/placeholder.png" alt="" />
<div class="upload-button">↑</div>
<input class="file-upload" type="file" accept="image/*"/>
</div>

您的div为空&没有任何运行函数的存在尝试以下代码:

<div class="upload-button">&nbsp;</div>

最新更新