How to determine when processing is complete for multiple ajax calls in javascript?

Assuming I have the following:

function main() {

  var finished = false;

  for(var i=0; i < 3; i++) {
    do(i);
  }
}

function do(i) {
  $.ajax({
   url:"myurl.com/"+i,
   datatype:"text/xml",
   success: function() {

        // Two more layers of multiple nested $.ajax elements here
   }
  })
}

Is there a way in which I can pop up a warning window after completing the "do" after three iterations? How? The syntax will help.

+5
source share
3 answers

Ajax call returns a jQuery Promise object. You can collect the output of each array and use it $.whento combine the promises package.

This code is the main idea of ​​what you want:

function main() {

  var finished = false;

  var defs = [];

  for(var i=0; i < 3; i++) {
    defs.push(do(i));
  }

  $.when.apply(null, defs).done(function() {
    //this code will only run when all ajax calls are complete
  });
}

function do(i) {
  var promise = $.ajax({
   url:"myurl.com/"+i,
   datatype:"text/xml",
   success: function() {

        // Two more layers of multiple nested $.ajax elements here
   }
  })

  return promise;
}

HTTP-, . , . , 2 ajax , ...

Firefox 2:  2
Firefox 3+: 6
Opera 9.26: 4
Opera 12:   6
Safari 3:   4
Safari 5:   6
IE 7:       2
IE 8:       6
IE 10:      8
Chrome:     6
+11

:

var complete = 0;

AJAX;

$.ajax({
  ... //other attributes,
  complete: function(){
    complete++;
    if (complete == 3) {
      alert('all completed');
    }
  }
});

AJAX. , , .

+2

You can use an array of statuses for this:

function main() {
  var ready = new Array(3);
  for (var i = 0; i < 3; i++) {
    ready[i] = false;
  }

  for (var i = 0; i < 3; i++) {
    do(i, ready);
  }
}

function do(i, ready) {
  $.ajax({
   url:"myurl.com/"+i,
   datatype:"text/xml",
   success: function() {
     // If there are multiple layers then the next statements should be executed in the last layer.
     ready[i] = true;
     if (isAllReady(ready)) {
       alert("All done!");
     }
   }
  })
}

function isAllReady(ready) {
  var allReady = true;
  for (var i = 0; i < 3; i++) {
    if (!ready[i]) {
      allReady = false;
    }
  }
  return allReady;
}
0
source

All Articles