簡體   English   中英

同時多個ajax請求

[英]Multiple ajax requests at the same time

我有一堆要使用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();

如果將async設置為true,則可以同時觸發多個。 瀏覽器將限制一次一次訪問的數量,具體取決於所使用的瀏覽器。

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

與ajax async工作與您所想的相反。

您應該將每個圖片的網址放在一個數組中。 如果您對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);
  });

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM