使用 jQuery 的并行异步 Ajax 请求 [英] Parallel asynchronous Ajax requests using jQuery

查看:40
本文介绍了使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆