开发者

In jquery how can I keep track of multiple ajax request called from one function

I'm using jquery and in one function I'm calling multiple function which are doing different ajax request for example

function contactForm(){
loadCountryList();
loadMyData();
checkUserType();

// doing my stuff

}

How can I know if all the ajax request are completed so that I start doing开发者_StackOverflow my stuff in the end? I don't want to call them one by one to minimize the request time. any suggestion will help me a lot.


You can use the global ajax handlers here, specifically .ajaxStop(), like this:

$(document).ajaxStop(function() {
  alert("All requests have completed!");
  //if you don't want to run it again, for example on future requests
  //then just unbind it like any other event :)
  $(this).unbind('ajaxStop');
});

You can also use it directly on an element you want to show for example:

$("#successDiv").ajaxStop(function() {
  $(this).fadeIn();
});

The .ajaxStop() handler (it's just an event) runs when all requests finish, not after each one.


// something like this

var countriesLoaded = false;
var dataLoaded = false; 
var userTypeChecked = false; 
var didRestOfStuff = false;

function readyForNextStage() {
  return countriesLoaded && dataLoaded && userTypeChecked;
}

// after you get a complete on each ajax callback 
countriesLoaded = true; // or dataLoaded and so on
if (readyForNextStage() && !didRestOfStuff) {
  didRestOfStuff = true;
  // do rest of stuff
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜