简体   繁体   中英

jQuery continue loop execution after ajax success

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
            }
        });
}

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);
            }
        });
    }
};

you can do something like this (pseudo-code):

var i =0;
doLoop();

function doLoop() {
   //exit condition
   if (i >= options.length) {
      return;
   }
   //loop body- call ajax
   $.ajax({
   //...
   success: function(data) {
      //do your thing
      i++;
      //go to next iteration of the loop
      doLoop();
   }
   });
}

Setting async to false will do that. Keep in mind that the web browser might lock up while the requests happen if you do them asynchronously.

jQuery.ajax({
    async : false,
    url: "ajax_file.php",
    data: //some data based on DOM tree
    success: function(data){
        //some DOM manipulation
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM