jQuery的递延 - 让链式Ajax调用结果链式、递延、结果、jQuery

2023-09-10 13:34:09 作者:妳是我的噩夢δ

下面的问题 - 我必须调用的次数AJAX功能号码,而当所有的功能都完成后,得到的所有结果存入数组。我想出了这一点:

following problem - I have to call ajax function number of times, and when all functions are complete, get all results into array. I came up with this:

function doAjax(xx){
var xdata = {json: $.toJSON({name: xx}),
            delay: 1};
return $.ajax({
    url:"/echo/json/",
    data:xdata,
    type:"POST"
});

}

var carr = [doAjax('a'),doAjax('b'),doAjax('c'),doAjax('d')]
var result = [];

$.when( carr )
    .done(function(data){
        console.log(data);
        $.each(data, function(ix,val){
            console.log(val.name);
        });
    });

小提琴在这里: http://jsfiddle.net/Fkd9n/

一切似乎是工作的罚款,该执行console.log(数据),写出来与响应文本的对象,但执行console.log(val.name)永远是不确定。因此,如何联合所有结果在一个阵列中,一旦所有的呼叫都做了什么?

All seems to be working fine, the "console.log(data)" writes out the objects with response text, but the "console.log(val.name)" is always "undefined". So how to joint all results in one array once all calls are done?

感谢您!

推荐答案

如果你知道有多少Ajax的电话,你有,只需使用$。当()

If you know how many Ajax-Calls you have, simply use $.when()

$.when(doAjax('a'),doAjax('b'),doAjax('c'),doAjax('d'))
.then(function(result_a,result_b,result_c,result_d) {
    console.log("Result from query a: " + result_a);
    console.log("Result from query b: " + result_b);
    console.log("Result from query c: " + result_c);
    console.log("Result from query d: " + result_d);
});

如果你不知道有多少Ajax的电话,你将有,你可以自行管理延期对象。

If you don't know how many ajax-calls you will have, you can manage the deferred objects by yourself.

// altered version of doAjax()
function doAjax(number,dObject) {
    var xdata = {json: $.toJSON({name: number}), delay: 1};
    $.ajax({
        url:"/echo/json/",
        data:xdata,
        type:"POST",
        success: function(data) {
            results.push(data);
            dObject.resolve();
        }
    });
}

// array that will contain all deferred objects
var deferreds = [];

// array that will contain all results
var results = [];

// make the ajax calls
for (var i = 0; i < someNumber; i++) {
    var dObject = new $.Deferred();
    deferreds.push(dObject);
    doAjax(i,dObject);
}

// check if all ajax calls have finished
$.when.apply($, deferreds).done(function() {
    console.log(results);
});

神奇自带的功能适用于(),这使得数组参数的函数。

The magic comes with the function apply() which makes an array to arguments for a function.