开发者

jQuery: How to fire event when all asynchronous calls return?

开发者 https://www.devze.com 2023-01-01 02:57 出处:网络
I have a jQuery application that loads data from five asynchronous server calls. I do not want to display any data until all five calls return. (I plan on displaying a Loading message until that happe

I have a jQuery application that loads data from five asynchronous server calls. I do not want to display any data until all five calls return. (I plan on displaying a Loading message until that happens.)

How can I detect when all five calls have returned? I considered having each callback method increment a variable (using jQuery's data() method, perhaps) and then waiting for the value to become 5. (I am not su开发者_JS百科re yet how I would listen for that event.) I do not think this is a very good solution, however. What would happen if two calls return at the same time?

Is there a better way to do this?


If you are already using jQuery for the AJAX calls, you can use $.ajaxStop() for this, it fires when all current calls come back, you can use it like this:

$("#loading").ajaxStop(function() {
  $(this).fadeOut();
});

This isn't really that different than .click() in terms that it's just an event, you can use the ajaxStop event yourself if you want, like this:

$("#loading").bind('ajaxStop', function() {
  $(this).fadeOut();
});
0

精彩评论

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