簡體   English   中英

JavaScript-數組中每個元素的HTTP請求

[英]JavaScript - HTTP Request for Each Element in Array

我有一個腳本,該腳本將HTTP請求發送到網站以獲取文檔,文檔ID保留在數組中。 我想為每個數組元素發送一個請求,並根據HEAD的狀態返回一條消息(例如200 OK)。

我的問題是,當我遍歷URL數組時,僅使用最后一個數組元素發送了多個請求,而沒有使用其他元素。

碼:

//send http request
function sendRequest(url) {
  var newRequest = new XMLHttpRequest();

  newRequest.onreadystatechange = function() {
    if(newRequest.readyState == 4) {
      if(newRequest.status == 200) {    
        console.log("loaded: " + url);
      } else {
        console.log("Failed to load: " + url);
      }
    }
  }

  newRequest.open("HEAD", url);
  newRequest.send();
}

//send request for each url in array
for(var i = 0; i < urlArray.length; i++) {
  //get document id and append to link
  var address = "https://www.adsa.co.uk/library.dr/docs.aspx?id=" + 
                urlArray[i];
  //console.log(address + "\n");
  sendRequest(address);
}

輸出(74是數組中最后一個元素的值):
此控制台消息產生urlArray.length次:

Failed to load: https://www.adsa.co.uk/library.dr/docs.aspx?id=74

為什么不為每個數組元素發送sendRequest()的想法?

Chrome(和Firefox)抱怨SSL證書無效,因此無法連接:

Failed to load resource: net::ERR_INSECURE_RESPONSE

感謝@Chris在評論中提醒我嘗試jsfiddle。

上面的代碼按原樣執行,遍歷數組,並為每個數組元素發送HTTP請求。 問題出在repl.it上 ,這是一個read-eval-print-loop編碼環境。 切換到jsbin和jsfiddle產生了預期的結果。

了解有關REPL的信息

暫無
暫無

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

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