Collect data from multiple sources
I have a need to collect data from multiple sources (xml or JSON format) via AJAX, and then run a function that consumes these data sets.
How can I check that all the AJAX calls are successful before the function is executed? Ideally, I'开发者_JAVA百科d like to keep async calls to minimize the response time.
Conceptually, it would work like this:
- Use async calls.
- Code a success handler for each call.
- When a call succeeds, you store the data from it in some common place and then record that this call has finished.
- At the end of each success handler, you check to see if all data is available now and, if so, you can a function to consume it.
Some pseudo code for an ajax call:
results = [];
$.ajax({
// other parameters here
success: function(data) {
results.push(data);
checkResults();
};
});
function checkResults() {
// if all five results are in, then we're ready to process them
if (results.length >= 5) {
processResults(results);
}
}
精彩评论