我有一个由 jQuery ajax 提交的表单,它有服务器端的错误验证。在发送之前我显示 一个 gif 加载器和一些加载文本,当验证在成功方法上发回时,我会显示相应的错误消息。 此消息在 x 秒后超时隐藏。无论如何,当我继续点击提交按钮时, setTimeout 本身很困惑,之前的也没有清除。这是我正在使用的代码:
编辑
$('form').on('submit', function(e) {
e.preventDefault();
var timer = null;
$.ajax({
beforeSend; function() {
$('.response').html('Processing form, please wait...');
},
success: function(data) {
if(data.error == true) {
$('.response').html('An error occurred.');
} else {
$('.response').html('Thank you. Form submitted successfully.');
}
if(timer) { clearTimeout(timer) };
timer = setTimeout(function() {
$('.response').html('* Indicates required fields.');
}, 10000);
}
});
});
任何建议表示赞赏。
最佳答案
timer
变量的作用域为您的 success
函数,因此当您的代码需要清除时,它始终 null
已达到旧超时。将 timer
声明移到 AJAX 调用之外,它应该可以工作。
var timer = null;
$.ajax({
beforeSend: function() { ... },
success: function(data) {
if(timer) { clearTimeout(timer) };
timer = setTimeout(myfunction, 10000);
}
});
关于javascript - ajax 上的 jQueryclearTimeout 成功变得困惑并且不清除以前的超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27585816/