我有一个由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);
}
});
});
任何建议表示赞赏。
答案 0 :(得分:2)
timer
变量的范围限定为success
函数,因此当您的代码清除旧的超时时,总是 null
。将timer
的声明移到AJAX调用之外,它应该可以正常工作。
var timer = null;
$.ajax({
beforeSend: function() { ... },
success: function(data) {
if(timer) { clearTimeout(timer) };
timer = setTimeout(myfunction, 10000);
}
});