是否可以运行所有Ajax调用下完成了循环语句后,code?语句、完成了、Ajax、code

2023-09-10 17:50:33 作者:XX睡着惹

我有一个for循环语句,每次循环将执行Ajax调用。

I have a for loop statement, each loop will execute an ajax call.

$.each(arr, function(i, v) {
    var url = '/xml.php?id=' + v;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'xml',
        success: function(xml) {
            if ($(xml).find('Lists').attr('total') == 1) {
                // some code here
            }
        },
        complete: function() {
            // some code here
        }
    })
})

我要为所有 Ajax调用循环下完成后,运行code,我试图将code以下到最后一行,它不被执行时,Ajax调用完成

I want to run code after all ajax call completed under the loop, I have tried to place the code below to last line, it is not executed when the ajax call completed

    if (i == arr.length - 1) {
        // some code here
    }

所以,如果我有循环的10倍,有Ajax调用的10倍。我想运行一个code后Ajax调用有10次完成,任何想法?

Therefore, if I have 10 times of loop, there are 10 times of ajax call. I want to run a code after there 10 times of ajax call completed, any ideas?

是它更好地使用 .ajaxComplete() .done()来实现呢?

Is it better to use .ajaxComplete() or .done() to achieve it?

感谢

推荐答案

请尝试使用 $。当()

var arr = [];
$.each(arr, function(i, v) {
    var url = '/xml.php?id=' + v;
    var xhr = $.ajax({
        url: url,
        type: 'GET',
        dataType: 'xml',
        success: function(xml) {
            if ($(xml).find('Lists').attr('total') == 1) {
                // some code here
            }
        },
        complete: function() {
            // some code here
        }
    });
    arr.push(xhr);
})

$.when.apply($, arr).then(function(){
    console.log('do')
})