我希望在ajax响应到来之前显示错误消息。尝试过使用以下代码:
$.ajax({
url: "user.php",
type: 'POST',
data: $('#forgot-form').serialize(),
beforeSend: function(){
$('#error').html("Please wait until your request is processed.");
setTimeout(function() { $("#error").html(''); }, 8000);
}
} ).done (function(data) {
/* I tried with the commented code also. But this section didn't worked */
//$('#error').html("Please wait until your request is processed.");
// setTimeout(function() { $("#error").html('Please wait until your request is processed.'); }, 8000);
if (data == "success") {
$('#user-login').val('');
$('#error').html("Please check your email to reset your password");
setTimeout(function() { $("#error").html(''); }, 5000);
} else if (data == "invalid") {
$('#error').html("Username or email doesnot exist");
setTimeout(function() { $("#error").html(''); }, 5000);
$('#user-login').focus();
return false;
}
});
在 user.php 页面中,如果用户详细信息正确,我将向用户发送电子邮件。所以反应来得很晚。直到那个时候我想要显示等待消息。
此代码正确显示等待消息。但在那之后有一个小延迟,然后只显示成功消息。我需要避免这个时间延迟。如何更改代码以避免延迟?
任何人都可以帮我这样做吗?提前谢谢。
答案 0 :(得分:1)
试试这个:
只需从发送回拨之前删除setTimeout()
即可。它将在#error中显示msg,它将在ajax完成后替换消息。
$.ajax({
url: "user.php",
type: 'POST',
data: $('#forgot-form').serialize(),
beforeSend: function(){
$('#error').html("Please wait until your request is processed.");
}
} ).done (function(data) {
/* I tried with the commented code also. But this section didn't worked */
//$('#error').html("Please wait until your request is processed.");
// setTimeout(function() { $("#error").html('Please wait until your request is processed.'); }, 8000);
if (data == "success") {
$('#user-login').val('');
$('#error').html("Please check your email to reset your password");
setTimeout(function() { $("#error").html(''); }, 5000);
}
else if (data == "invalid") {
$('#error').html("Username or email doesnot exist");
setTimeout(function() { $("#error").html(''); }, 5000);
$('#user-login').focus();
return false;
}
});
答案 1 :(得分:0)
删除beforeSend()
并在$.ajax
来电之前设置等待消息。
$('#error').html("Please wait until your request is processed.");
$.ajax({
url: "user.php",
type: 'POST',
data: $('#forgot-form').serialize(),
}).done (function(data) {
if (data == "success") {
$('#user-login').val('');
$('#error').html("Please check your email to reset your password");
setTimeout(function() { $("#error").html(''); }, 5000);
} else if (data == "invalid") {
$('#error').html("Username or email doesnot exist");
setTimeout(function() { $("#error").html(''); }, 5000);
$('#user-login').focus();
return false;
}
});