动态多递延jQuery的Ajax调用 [英] Dynamic multiple Deferred jQuery Ajax calls

查看:156
本文介绍了动态多递延jQuery的Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用递延模式从jQuery的 http://api.jquery.com/jQuery.when/ ,我想使多个JSONP AJAX调用和等待结果移动到下一个步骤。我可以使用呼叫固定量做到这一点,因为我可以设置解决了参数的参数个数在.done()延迟对象。但是,在我的应用程序也无法正常工作,因为调用的数量是动态的,总是未知的。

Using the Deferred pattern from jQuery http://api.jquery.com/jQuery.when/, I am trying to make multiple jsonp ajax calls and wait for the results before moving to the next step. I can accomplish this using a fixed amount of calls because I can set the number of resolved argument parameters in the ".done()" deferred object. But in my application it doesn't work because the number of calls is dynamic and always unknown.

这首简单的例子作品,因为我可以设置args来数在.done()解决功能。我知道我需要两个,因为有在。当两个调用():

This first simplified example works because I can set the number of args in the .done() resolved function. I know I need two because there are two calls in the .when():

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

这是我需要的,但不能让它开始工作:

This is what I need but can't get it to work:

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
});

感谢有这方面的帮助!

Thanks for any help on this!

推荐答案

您可以使用<一个href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/arguments">arguments,这是持有对象传递给函数的所有参数的一个特殊的王

You can use arguments, which is a special king of object holding all arguments passed to a function

$.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)
});

这篇关于动态多递延jQuery的Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆