I have a script that sends HTTP requests to a website to get documents, the document IDs are kept in an array. I want to send a request for each array element and return a message based on the status from the HEAD (e.g. 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.
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):
This console message is produced urlArray.length
times:
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?