How do I know when an ajax request is complete in jquery
I have two post requests I'm making utilizing jquery and a method that uses the result of those posts. So the code works like this:
post1
post2
function
How do I get the code to wait until both post1 and post2 are completed before calling the function? I tried doing a while loop to see if the data from post1 and post2 had both been set, but it hangs the browser. I could call them synchronously, but that would be slower than setting off both requests and waiting for them to complete. This would be easy to solve in any multithreaded language except for JavaScript si开发者_开发百科nce officially it's not suppose to be multithreaded and thus has no support for waiting for a series of "threads" to complete.
Keep a count of the requests, and in your callback modify it then see if there are any left to run.
var count = 2;
var callback = function () {
count--;
if (!count) {
both_ajax_called_successful();
}
};
jQuery.ajax({url: 'example1', success: callback});
jQuery.ajax({url: 'example2', success: callback});
Declare a counter with the value being the number of requests and subtract one off its value every time you get a response. When the value is 0, all requests should be done.
精彩评论