在for循环语句下完成所有ajax调用后,是否可以运行代码?

Cha*_*ung 3 ajax each jquery

我有一个for循环语句,每个循环都会执行一个ajax调用.

$.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
        }
    })
})
Run Code Online (Sandbox Code Playgroud)

我想在循环下完成所有 ajax调用之后运行代码,我试图将下面的代码放到最后一行,当ajax调用完成时不执行

    if (i == arr.length - 1) {
        // some code here
    }
Run Code Online (Sandbox Code Playgroud)

因此,如果我有10次循环,则有10次ajax调用.我想在ajax调用完成10次之后运行代码,有什么想法吗?

使用.ajaxComplete().done()实现它更好吗?

谢谢

Aru*_*hny 13

尝试使用$ .when()

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')
})
Run Code Online (Sandbox Code Playgroud)