【发布时间】:2016-04-23 10:31:02
【问题描述】:
这是我的问题,Ajax 运行良好,可以处理所有数据,但由于某种原因,我目前忽略了它,它没有显示加载器和成功 div。
我的 html 类似于
<form id="msform" action="#">
<fieldset>
<!-- some fields -->
<input type="submit" Value="submit">
</fieldset>
</form>
<div id="processing" class="row" style="display:none"></div>
<div id="apf-response" class="row" style="display:none"></div>
我的 jQuery / AJAX 看起来像:
$(document).ready(function(){
$('#msform').submit(function(event){
event.preventDefault();
apfaddpost();
})
})
function apfaddpost() {
var fd = new FormData($('#msform')[0]);
fd.append( "main_image", $('#main_image')[0].files[0]);
fd.append( "action", 'apf_addpost');
//Append here your necessary data
jQuery.ajax({
type: 'POST',
url: apfajax.ajaxurl,
data: fd,
processData: false,
contentType: false,
beforeSend: function(){
//here should be the issue. I'm hiding the form and showing the loader div
$('#msform').hide();
$('#processing').show();
},
success: function(data, textStatus, XMLHttpRequest) {
//when it's completed hide loader and show success message
$('#processing').hide();
$('#apf-response').show();
var id = '#success';
jQuery(id).html('');
jQuery(id).append(data);
resetvalues($('#msform'));
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
这是正确的方法吗?我做错了什么?
编辑
event.preventDefault(); 或 action="#" 可能会给出这个问题吗?
已解决
我已将我的 jQuery 代码更改为
function apfaddpost() {
var fd = new FormData($('#msform')[0]);
fd.append( "main_image", $('#main_image')[0].files[0]);
fd.append( "action", 'apf_addpost');
$('#form-container').hide();
$('#processing').show();
var postProject = $.ajax({
type: 'POST',
url: apfajax.ajaxurl,
data: fd,
processData: false,
contentType: false,
});
postProject.done(function(data, textStatus, XMLHttpRequest) {
$('#processing').hide();
$('#apf-response').show();
var id = '#success';
jQuery(id).html('');
jQuery(id).append(data);
resetvalues($('#msform'));
});
postProject.fail(function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
});
}
成功了!
【问题讨论】:
-
试着把 $("#processing").show();在 ajax 请求开始之前。
-
@DharaParmar 不幸的是,把它放在前面是行不通的
-
您能否确认在进行 AJAX 调用时触发了成功处理程序?此外,如果使用链接到 AJAX 对象而不是使用嵌套的
success或error处理程序的承诺,例如.done()和.fail(),实际上会更容易。 -
@Terry 是的 Ajax 处理程序已成功触发。如果我在控制台中更改 display:none,我会看到该消息。我尝试用
.done()和.fail更改它。总是成功,但仍然没有显示加载器和消息。 -
@Terry 其实感谢您的建议!我在使用
.done()和.fail()时犯了一些错误。现在它正在工作!太好了。