admin管理员组

文章数量:1243170

I'm making in code a few requests with JQuery and get. It looks like:

$.get('address1', function() { ... });
$.get('address2', function() { ... });
$.get('address3', function() { ... });

// This code should be runned when all 3 requests are finished
alert('Finished');

So, are there any ways to detect whether there is still processing request and run marked code only when all 3 requests are finished.

Thanks.

I'm making in code a few requests with JQuery and get. It looks like:

$.get('address1', function() { ... });
$.get('address2', function() { ... });
$.get('address3', function() { ... });

// This code should be runned when all 3 requests are finished
alert('Finished');

So, are there any ways to detect whether there is still processing request and run marked code only when all 3 requests are finished.

Thanks.

Share Improve this question edited Jul 23, 2011 at 1:45 genesis 51k20 gold badges98 silver badges126 bronze badges asked Jul 16, 2011 at 12:59 Max FraiMax Frai 64.3k81 gold badges202 silver badges311 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 13

You can make use of deferred objects [docs] introduced in jQuery 1.5:

$.when(
    $.get('address1', function() { ... }),
    $.get('address2', function() { ... }),
    $.get('address3', function() { ... })
).then(function() {
    alert('Finished');
});

Reference: jQuery.when

The jQuery learning center has a nice introduction to deferred objects / promises.

 var isFinished = [];

$.get('address1', function() { isFinshed.push["address1"]; allDone(); });
$.get('address2', function() { isFinshed.push["address2"]; allDone(); });
$.get('address3', function() { isFinshed.push["address3"]; allDone();});

var allDone = function(){
    if(isFinished.length < 3)return

    alert('Finished');
};
var fin1 = false;
var fin2 = false;
var fin3 = false;

$.ajax({
  url: "address1",
  success: function(){
    fin1 = true;
    fnUpdate();
  }
});

$.ajax({
  url: "address2",
  success: function(){
    fin2 = true;
    fnUpdate();
  }
});

$.ajax({
  url: "address3",
  success: function(){
    fin3 = true;
    fnUpdate();
  }
});

function fnUpdate(){
  if(fin1 && fin2 && fin3){
    alert('fin');
  }
}
var count = 0;
$.get('address1', function() { count++; ... });
$.get('address2', function() { count++; ... });
$.get('address3', function() { count++; ... });

var int = setInterval(function() {
    if (count === 3) {
        clearInterval(int);
        alert('done');
    }
}, 10);

本文标签: javascriptHow to call alert after all ajax requests are doneStack Overflow