从阵列和手柄回调完成后多Ajax调用 [英] Multiple ajax calls from array and handle callback when completed
问题描述
我已经使用jQuery的承诺稍前 - 但我无法将它应用到这种情况。我preFER使用$。当()和$ .done()方法来实现这一点。
据我了解,我需要建立一个$ .Deferred对象,它记录的请求,并在这些请求完成后 - 火回调。在回调低于我的code是射击的在的Ajax请求,而不是之后 - 也许我只是需要一些睡眠
我知道我的code是不完整的我一直在努力将其与另外的for循环使用。
http://jsfiddle.net/whiteb0x/MBZEu/
VAR列表= ['OBJ1','OBJ2,obj3','OBJ4','obj5'];
VAR回调=函数(){
警报(完成);
};
变种请求= [];
VAR ajaxFunction =函数(OBJ,successCallback,errorCallback){
对于(i = 0; I< list.length;我++){
$阿贾克斯({
URL:URL,
成功:函数(){
requests.push(本);
}
});
}
};
$。当($阿贾克斯(),ajaxFunction)。然后(函数(结果){回调()});
的参数 $。当
应 $的返回值。 AJAX
,这也并不需要单独称为 - 这是没有意义的。你想是这样的:
为(i = 0; I< list.length;我++){
requests.push($阿贾克斯(...)。);
}
$ .when.apply(不确定,请求)。然后(...)
而之所以。适用
是必要的,因为 $。当
可以采用多个参数,而不是一个数组的参数。 。适用
扩展本质上是:
$。当(请求[0],要求[1],...)
此还假定请求可以以任何顺序完成。
http://jsfiddle.net/MBZEu/4/ - 请注意,完成已登录到控制台毕竟成功的消息。
I have used promises in jQuery slightly before - but I am having trouble applying it to this scenario. I prefer to use the $.when() and $.done() methods to achieve this.
From what I understand I need to build a $.Deferred object which logs the requests and when those requests are finished - fire the callback. In my code below the callback is firing before the ajax requests and not after - maybe I just need some sleep
I know my code is incomplete I have been struggling to apply it with the addition of the for loop.
http://jsfiddle.net/whiteb0x/MBZEu/
var list = ['obj1', 'obj2', 'obj3', 'obj4', 'obj5'];
var callback = function() {
alert("done");
};
var requests = [];
var ajaxFunction = function(obj, successCallback, errorCallback) {
for(i = 0; i < list.length; i++) {
$.ajax({
url: 'url',
success: function() {
requests.push(this);
}
});
}
};
$.when($.ajax(), ajaxFunction).then(function(results){callback()});
The arguments to $.when
should be the return value of $.ajax
, which also doesn't need to be called separately -- that makes no sense. You want something like this:
for (i = 0; i < list.length; i++) {
requests.push($.ajax(...));
}
$.when.apply(undefined, requests).then(...)
The reason that .apply
is needed is because $.when
can take multiple arguments, but not an array of arguments. .apply
expands essentially to:
$.when(requests[0], requests[1], ...)
This also assumes that the requests can be completed in any order.
http://jsfiddle.net/MBZEu/4/ -- notice that 'done' is logged to the console after all of the success messages.
这篇关于从阵列和手柄回调完成后多Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!