【问题标题】:Multiple ajax requests at the same time同时多个ajax请求
【发布时间】:2017-03-04 03:13:48
【问题描述】:

我有一堆想用 ajax 读取的图像。 如果我知道每张图片的 url,我怎样才能同时发出 3 个图像 ajax 请求,然后再获取下 3 个,直到我拥有它们?

这是我的一张图片的 ajax 函数

  var image_url = images[i];
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200){
      console.log(xhr.response, typeof xhr.response);

    }
  }

  xhr.open('GET', image_url);
  xhr.responseType = 'blob';
  xhr.send();

【问题讨论】:

  • 有什么理由限制同时请求 3 个?
  • 不让服务器超载
  • 您正在寻找Promise.all。下面的解决方案使用 JQuery,但这可以用 vanilla JS 完成

标签: javascript ajax parallel-processing blob


【解决方案1】:

如果您将async 设置为true,您可以同时触发多个。浏览器将限制一次有多少个,具体取决于使用的是哪一个。

$.ajax({
    type: "GET",
    async: false,
    url: "foo2.php"
    });

async 与 ajax 的作用与您的想法相反。

【讨论】:

    【解决方案2】:

    您应该将每个图像的 URL 放在一个数组中。 如果你对 jQuery 没有疑虑,你应该使用 $.get 因为在这种情况下它会帮助很多处理。然后在递归函数中调用它。这是伪代码,我没有测试过。

    var imageUrls = [];//populate with your URLs
    getImage(0);
    getImage(1);
    getImage(2);
    
    
    var getImage = function(iteration){
      $.get(imageUrls[iteration], function(data){
         //handle the image
         //call the function again with the next index
         getImage(iteration+3);
      });
    
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-28
      • 2014-10-11
      • 1970-01-01
      • 2013-01-21
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多