[英]error callback function is fired even if request is successful
我有一个使用ajax发送邮件的脚本。 我已经通过检查将接收邮件的电子邮件进行了测试,并且足够真实,ajax请求成功。 我还检查了Firefox浏览器的控制台窗口,它也向我显示一条成功消息。 但是我的问题是, error
回调函数被触发,而不是done
回调函数。 您可能都想知道为什么我仍在使用error
功能而不是fail
。 原因是因为当我尝试使用fail
功能时,它不会触发我在其中设置的警报框。 因此,我要做的是返回并再次使用error
功能,因为至少它会触发我创建的警报框。
这是脚本:
<script type="text/javascript">
var submitButton = $('#submit'); // Variable to cache button element
var alertBox1 = $('.success'); // Variable to cache meter element
var alertBox2 = $('.alert');
var closeButton1 = $('.close1'); // Variable to cache close button element
var closeButton2 = $('.close2'); // Variable to cache close button element
$( function(){
$( '#contactform' ).submit( function(e){
e.preventDefault();
console.log( 'hello' );
var formData = $( this ).serialize();
console.log( formData );
$.ajax({
type: 'POST',
url: 'send.php',
data: formData,
dataType: 'json',
done: function(){
$(submitButton).fadeOut(500); // Fades out submit button when it's clicked
setTimeout(function() { // Delays the next effect
$(alertBox1).fadeIn(500); // Fades in success alert
}, 500);
},
error: function(){
$(submitButton).fadeOut(500); // Fades out submit button when it's clicked
setTimeout(function() { // Delays the next effect
$(alertBox2).fadeIn(500); // Fades in fail alert
}, 500);
}
});
});
$(closeButton1).click(function() { // Initiates the reset function
$(alertBox1).fadeOut(500); // Fades out success message
setTimeout(function() { // Delays the next effect
$('input, textarea').not('input[type=submit]').val(''); // Resets the input fields
$(submitButton).fadeIn(500); // Fades back in the submit button
}, 500);
return false; // This stops the success alert from being removed as we just want to hide it
});
$(closeButton2).click(function() { // Initiates the reset function
$(alertBox2).fadeOut(500); // Fades out success message
setTimeout(function() { // Delays the next effect
$('input, textarea').not('input[type=submit]').val(''); // Resets the input fields
$(submitButton).fadeIn(500); // Fades back in the submit button
}, 500);
return false; // This stops the fail alert from being removed as we just want to hide it
});
});
</script>
造成这种情况的原因似乎是什么? 只是重申一下,我尝试使用fail
而不是error
回调函数,因为这是我在Internet上找到的答案之一,并且还因为我知道error
函数已被弃用这一事实。 但是由于上面提到的原因,我别无选择,只能使用它。
如果您参考文档,则不能在ajax函数内部使用done作为回调。 在ajax调用结束时使用成功或添加完成。
$.ajax({
// url, data etc
success: function() {
//success handler
},
error:function(){
//Error handler
}
});
(OR)
$.ajax({
// ajax related codes
}).done(function(){
//callback
});
另外,如果您不是真的从服务器返回JSON dataType: 'json',
从ajax调用中删除dataType: 'json',
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.