是否可以运行所有Ajax调用下完成了循环语句后,code? [英] Is it possible to run code after all ajax call completed under the for loop statement?

查看:121
本文介绍了是否可以运行所有Ajax调用下完成了循环语句后,code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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')
})

这篇关于是否可以运行所有Ajax调用下完成了循环语句后,code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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