等到所有多个异步ajax调用完成 [英] Wait till all multiple asynchronous ajax call are completed
问题描述
你好,我有多个ajax调用,我想做的是异步地激发它们,然后等到它们全部完成后再处理返回的数据.我尝试使用$ .when,但无济于事.这是我的代码:
Hello I have multiple ajax call, what I wanted to do is to fire all of them asynchronously then wait till all of them are finished before processing the returned data. I tried using $.when but to no avail. Here is my code:
//form_identifier_list is my flag to get the multiple forms in my html page
function test(form_identifier_list){
var deffereds = [];
$.each(form_identifier_list, function(key,value){
var this_form = $(this).parents('.ajaxed_form');
deffereds.push( $.post($(this_form).attr("action"), $(this_form).serializeForm()) );
});
$.when.apply($, deffereds).done(function(){
//how to output response obj?? i tried console.log(data) to no avail
}).fail(function(){
}).always(function(){
});
}
我还注意到我的Ajax请求没有响应(我已经在浏览器中验证了响应).
I also noticed my ajax requests do not have reponse (which i verified on my browser).
是否有一种方法可以使多个ajax调用异步触发,然后等到它们全部完成然后访问数据?
Is there a way to make multiple ajax calls fire asynchronously and then wait till all of them are finished then access the data?
谢谢
推荐答案
在 when ,其中有一段内容:
如果将多个Deferred对象传递给 jQuery.when(),该方法从新的母版"返回Promise 跟踪所有Deferred的聚合状态的Deferred对象 它已通过.
In the case where multiple Deferred objects are passed to jQuery.when(), the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed.
从jQuery 1.5开始,由$ .ajax()返回的jqXHR对象实现了 承诺界面
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface
因此我们可以将ajax
的返回值分配给一个变量,然后将这些变量传递给.when
.
So we can just assign the return value of the ajax
to a variable and pass those variables into the .when
.
要稍微扩展.when
页上给出的示例并集成任意数量的ajax调用,可以执行以下操作:
To expand slightly on the example given on the .when
page and integrate any number of ajax calls, you can do something like this:
var ajaxes = [];
for(var i=0; i<10; i++) {
ajaxes.push($.ajax('a.php', {data: {t: i}}));
}
$.when.apply($, ajaxes)
.done(function(){
for(var i=0;i<arguments.length; i++) {
$('#output').append(arguments[i] + "<br>");
};
});
如果您知道已知数量的ajax调用,它将变得更简单...您可以执行以下操作:
If you have a known number of ajax calls, it gets a little simpler...you can do something more like this:
var a1 = $.ajax(...);
var a2 = $.ajax(...);
var a3 = $.ajax(...);
$.when(a1,a2,a3).done(function(o1, o2, o3) {
$('#output').append(o1).append(o2).append(o3);
});
第一个示例基本上是在做同样的事情.
The first example is basically doing the same thing.
这篇关于等到所有多个异步ajax调用完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!