jQuery的继续阿贾克斯成功后,循环执行继续、jQuery、阿贾克斯

2023-09-11 01:07:50 作者:﹎忘钓过袪

我在一个循环中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);
            }
        });
    }
};