使用jQuery并行异步Ajax请求 [英] Parallel asynchronous Ajax requests using jQuery
本文介绍了使用jQuery并行异步Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想更新基于多个AJAX / JSON请求的结果页面。使用jQuery,我可以链的回调,像这样很简单的精简例如:
I'd like to update a page based upon the results of multiple ajax/json requests. Using jQuery, I can "chain" the callbacks, like this very simple stripped down example:
$.getJSON("/values/1", function(data) {
// data = {value: 1}
var value_1 = data.value;
$.getJSON("/values/2", function(data) {
// data = {value: 42}
var value_2 = data.value;
var sum = value_1 + value_2;
$('#mynode').html(sum);
});
});
然而,这导致请求产生了串联。我宁愿一个方法,使并行的要求,并执行网页更新后,所有完成。有没有办法做到这一点?
However, this results in the requests being made serially. I'd much rather a way to make the requests in parallel, and perform the page update after all are complete. Is there any way to do this?
推荐答案
尝试这种解决方案,它可以支持并行查询任何具体的数字:
Try this solution, which can support any specific number of parallel queries:
var done = 4; // number of total requests
var sum = 0;
/* Normal loops don't create a new scope */
$([1,2,3,4,5]).each(function() {
var number = this;
$.getJSON("/values/" + number, function(data) {
sum += data.value;
done -= 1;
if(done == 0) $("#mynode").html(sum);
});
});
这篇关于使用jQuery并行异步Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文