动态多个延迟jQuery Ajax调用

使用jQuery http://api.jquery.com/jQuery.when/中的Deferred模式,我尝试进行多个jsonp ajax调用并等待结果,然后再转到下一步。 我可以使用固定数量的调用来完成此操作,因为我可以在“.done()”延迟对象中设置已解析参数的数量。 但是在我的应用程序中它不起作用,因为调用的数量是动态的并且总是未知的。

第一个简化示例有效,因为我可以设置.done()已解析函数中的args数。 我知道我需要两个,因为.when()中有两个调用:

$.when( $.ajax( url1 ), $.ajax( url2 ) ).done(function( a1, a2 ) { var data = a1[ 0 ] + a2[ 0 ]; }); 

这是我需要的但却无法使用它:

 var urls = GetUrlList(); // returns array of urls to json service var requests = []; // hold ajax request for (i = 0; i < urls.length; i++) { requests.push($.ajax(url[i])); } $.when.apply($, requests).done(function ("what goes here?") { // Need to get the data returned from all ajax calls here }); 

感谢您的帮助!

你可以使用参数 ,它是一个特殊的对象王,包含传递给函数的所有参数

 $.when.apply($, requests).done(function () { console.log(arguments); //it is an array like object which can be looped var total = 0; $.each(arguments, function (i, data) { console.log(data); //data is the value returned by each of the ajax requests total += data[0]; //if the result of the ajax request is a int value then }); console.log(total) });