【问题标题】:Dynamic multiple Deferred jQuery Ajax calls动态多个延迟的 jQuery Ajax 调用
【发布时间】:2013-11-06 00:26:53
【问题描述】:

使用来自 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
});

感谢您对此的任何帮助!

【问题讨论】:

    标签: javascript jquery ajax jsonp deferred


    【解决方案1】:

    你可以使用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)
    });
    

    【讨论】:

    • 当您至少有两个请求要发送时,这很有效。否则,当它是一个或多个查询时,您会得到不一致的行为:(
    • 参数链接已过时并指向已弃用的功能。 updated link is this
    • 这并不完美。我用 1 个参数调用它,但到达了 2 个参数,其中第二个是字符串文字 success
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 2014-03-15
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多