[英]How to stop AJAX making multiple calls?
I'm using the jquery countdown timer plugin ( http://keith-wood.name/countdown.html ) to display the time. 我正在使用jquery倒数计时器插件( http://keith-wood.name/countdown.html )显示时间。 I'm calling a function to add more time on callback event 'onTick'. 我正在调用一个函数,以在回调事件“ onTick”上添加更多时间。 When the time countdowns to 00:00:00, the function will make an ajax call to add extra time. 当时间倒计时至00:00:00时,该函数将进行ajax调用以添加额外的时间。 It's working fine but every time the timer equals 00, ajax is making multiple calls (>15). 它工作正常,但是每次计时器等于00时,ajax都会进行多次调用(> 15)。 How can I make it to send just one call? 我怎样才能只发送一个电话? I tried doing async: false but still it's making multiple calls. 我尝试执行异步操作:false,但仍在进行多个调用。 Thank you. 谢谢。
$(this).countdown({ until: time, format: 'HMS', onTick: addExtraTime });
function addExtraTime() {
if ($.countdown.periodsToSeconds(periods) === 00) {
var postValue = { ID: id }
if (!ajaxLoading) {
ajaxLoading = true;
$.ajax({
url: "@Url.Action("AddExtraTime", "Home")",
type: 'post',
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(postValue),
success: function() {
// show success
},
error: function(data) {
// show error
}
});
ajaxLoading = false;
}
}
}
You have a variable, ajaxLoading
, that you use to determine if an Ajax request is in flight but you set it to false
immediately after calling $.ajax()
instead of when you get a response. 您有一个变量ajaxLoading
,用于确定Ajax请求是否正在运行,但在调用 $.ajax()
而不是在获得响应时立即将其设置为false
。 Set it to false
inside your success and error handlers instead. 在成功和错误处理程序中将其设置为false
。
You're setting ajaxLoading = false;
您正在设置ajaxLoading = false;
even when the ajax request is still being done, set it to false after the request is completed 即使ajax请求仍在完成,在请求完成后将其设置为false
if (!ajaxLoading) {
ajaxLoading = true;
$.ajax({
url: "@Url.Action("AddExtraTime", "Home")",
type: 'post',
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(postValue),
success: function() {
// show success
},
error: function(data) {
// show error
}
complete: function(){
ajaxLoading = false;
}
});
//ajaxLoading = false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.