![](/img/trans.png)
[英]jQuery: how to check to make sure all asynchronous actions have been completed
[英]Make sure all async calls have been completed in jQuery
我有一个webapp正在使用jQuery:s $ .get和$ .post方法进行一堆异步API调用。 在激活按钮(显示:无/阻止)之前,我需要确保所有这些操作均已成功完成(HTTP状态代码200)。
有没有一种方法可以确保没有未完成的异步调用在jQuery中开箱即用? 还是我自己要对此进行跟踪?
我正在使用jQuery v1.8.3。
您可以创建一个“ Master Deferred”,仅在所有其他Deferred(AJAX请求)成功完成后才能解决。
jQuery.when(jQuery.get('/foo'), jQuery.post('/bar'), jQuery.get('/baz')).done(function () {
$('button').show();
});
语法是将每个Deferred
作为参数传递给jQuery.when()
,它返回一个Deferred
,当一个失败或全部完成时解析。
如果您事先不知道有多少个AJAX请求,已经将它们放在一个数组中,或者只是不想使用以上内容,则可以使用Function.apply
;
var ajaxRequests = [jQuery.get('/foo'), jQuery.post('/bar'), jQuery.get('/baz')];
jQuery.when.apply(jQuery, ajaxRequests).done(function () {
$('button').show();
});
有关更多信息,请参见http://api.jquery.com/jQuery.when或http://www.mattlunn.me.uk/blog/2014/01/tracking-joining-parallel-ajax-requests-with- jQuery / (我的博客)
在这篇文章中 ,您应该能够使用相同的代码(不过,您不需要abortAll
函数,因此已将其删除,并添加了对活动请求的检查):
$.xhrPool = [];
$.ajaxSetup({
beforeSend: function(jqXHR) {
$.xhrPool.push(jqXHR);
},
complete: function(jqXHR) {
var index = $.xhrPool.indexOf(jqXHR);
if (index > -1) {
$.xhrPool.splice(index, 1);
}
if ($.xhrPool.length > 0) {
//There are still active requests - keep the button hidden
} else {
//There's no more active requests - show the button
}
}
});
这将适用于所有通过jQuery请求的ajax请求,包括$.get
, $.post
和$.ajax
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.