Multiple ajax calls from array and handle callback when completed

一世执手 提交于 2019-11-27 19:07:56

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.

I share an easy example that could help you to handle multiple requests and their responses:

var arr = [
    $.ajax({url:"test1.php"}),
    $.ajax({url:"test2.php"}),
    $.ajax({url:"test3.php"})
];
$.when.apply( undefined, arr ).then(function() {
    var objects=arguments;
    console.dir(objects);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!