开发者

How can I trigger a function when all my ajax calls are finished?

I'm calling several ajax search services with jQuery and would like to trigger a function that merges the results when all the calls are finished (some kind of callback func开发者_开发问答tion waiting for all callbacks to have returned). What's the best method to achieve that?

thanks

jul


One method I've seen used in the past is a counter:

var counter = 3;

$.ajax({
  // ..
  success: function() {
    if(--counter == 0) handleComplete();
    // ...
  }
});

// 2 other similar ajax calls here

function handleComplete() {
  // this is done when all are complete
}

Obviously, you'll want to handle errors too.


Increase a local variable when making an ajax call. Decrease it on the return callback. When one callback triggers the var back to 0, call the global result callback. You can alternatively use an array of calls you made, or a stack, etc...


I would probably use the ajaxComplete event. You'll have to have your own logic for knowing when the series starts and finishes, but that presumably will come out of your application logic anyway.

Here's a trivial example (live copy):

jQuery(function($) {
  var count = 0;

  display("Hooking up handler");
  $(document.body).ajaxComplete(function(event, xhr, options) {
    ++count;
    display("Got a completion, new counter value = " + count);
  });
  display("Doing three ajax requests.");
  $.ajax({
    url: "http://jsbin.com/aciyu4"
  });
  $.ajax({
    url: "http://jsbin.com/aciyu4"
  });
  $.ajax({
    url: "http://jsbin.com/aciyu4"
  });

  function display(msg) {
    $("<p/>").html(msg).appendTo(document.body);
  }
});​

In that example, I'm keeping track of how many requests have completed using a count variable over which the registered handler is a closure (and so has access to it).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜