jQuery的继续阿贾克斯成功后,循环执行 [英] jQuery continue loop execution after ajax success

查看:191
本文介绍了jQuery的继续阿贾克斯成功后,循环执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个循环中jQuery的AJAX调用。不过,我不希望这些AJAX调用同时进行,我首先需要的AJAX调用才去到下才能完成。

I have a jQuery ajax call in a loop. However I do not want those ajax calls to be made simultaneously, I need the first ajax call to finish before going on to the next.

for (var i = 0; i < options.length; i++) {  
        jQuery.ajax({
            url: "ajax_file.php",
            data: //some data based on DOM tree
            success: function(data){
                //some DOM manipulation
            }
        });
}

我想循环继续DOM操作的成功是仅执行后(因为Ajax调用依赖于DOM树)执行。 从理论上讲,我知道我可以设置在Ajax调用是异步:假的,但不推荐,因为它可以冻结浏览器

I want the loop to continue executing only after the DOM manipulation in SUCCESS was executed (because the ajax call depends on the DOM tree). In theory I know I could set the ajax call to be async:false, but it is not recommended as it can freeze the browser.

推荐答案

由于异步:假始终是一个坏主意,我建议是这样的:

Because async: false is always a bad idea, I'd recommend something like this:

var recur_loop = function(i) {
    var num = i || 0; // uses i if it's set, otherwise uses 0

    if(num < options.length) {
        jQuery.ajax({
            url: "ajax_file.php",
            data: //some data based on DOM tree
            success: function(data){
                recur_loop(num+1);
            }
        });
    }
};

这篇关于jQuery的继续阿贾克斯成功后,循环执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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