简体   繁体   English

JavaScript-数组中每个元素的HTTP请求

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

I have a script that sends HTTP requests to a website to get documents, the document IDs are kept in an array. 我有一个脚本,该脚本将HTTP请求发送到网站以获取文档,文档ID保留在数组中。 I want to send a request for each array element and return a message based on the status from the HEAD (eg 200 OK). 我想为每个数组元素发送一个请求,并根据HEAD的状态返回一条消息(例如200 OK)。

The problem I have is that when I loop through the URL array, multiple requests are sent using only the last array element, no other element is used. 我的问题是,当我遍历URL数组时,仅使用最后一个数组元素发送了多个请求,而没有使用其他元素。

Code: 码:

//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);
}

Output (74 is the value of the last element in the array): 输出(74是数组中最后一个元素的值):
This console message is produced urlArray.length times: 此控制台消息产生urlArray.length次:

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

Any ideas why the sendRequest() is not sent for each array element? 为什么不为每个数组元素发送sendRequest()的想法?

Chrome(和Firefox)抱怨SSL证书无效,因此无法连接:

Failed to load resource: net::ERR_INSECURE_RESPONSE

Thanks to @Chris in the comments for alerting me to try jsfiddle. 感谢@Chris在评论中提醒我尝试jsfiddle。

The above code executes as it should, it iterates over the array and sends an HTTP request for each array element. 上面的代码按原样执行,遍历数组,并为每个数组元素发送HTTP请求。 The issue was with repl.it , a read-eval-print-loop coding environment. 问题出在repl.it上 ,这是一个read-eval-print-loop编码环境。 Switching to jsbin and jsfiddle produced expected results. 切换到jsbin和jsfiddle产生了预期的结果。

Read about REPL . 了解有关REPL的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM