26

使用 jQuery http://api.jquery.com/jQuery.when/中的延迟模式,我正在尝试进行多个 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
});

感谢您对此的任何帮助!

4

1 回答 1

37

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

$.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)
});
于 2013-10-27T03:41:09.347 回答