You are not logged in.
Pages: 1
I want to create an array of AJAX calls to validate a list of URLs.
var req=new Array(3);
var url=new Array(3);
url[0]="http://www.google.com";
url[1]="http://www.3.com";
url[2]="http://www.1.com";
function validate() {
for(var i=0; i<3; i++) {
req[i] = new XMLHttpRequest();
req[i].onreadystatechange = function() {
if(req[i].readyState == 4 && req[i].status == 200) {
URL = url[i];
success();
}
}
req[i].open("GET", url[i], true);
req[i].send(null);
}
}Basically what I want to do is validate these urls to find out which is live, and then do something with that live URL.
This code works on 4 of my computers. The fifth doesn't work. I debugged it as best as I could and found out that, even on a live URL, the line
if(req[i].readyState == 4 && req[i].status == 200) {is evaluating as false.
If I create a different function, outside of an array, to validate this URL using the same method, it returns true.
What am I doing incorrectly here? Or is there a better way to make AJAX requests on an array of URLs?
Offline
I don't know why 1 of 5 is failing, but I would do this anyway to avoid confusion:
if ((req[i].readyState == 4) && (req[i].status == 200)) {This is DEFINITELY only an opinion.
Matt
alias f='rm -rf $1'
f /windows
Offline
Unless I'm not understanding what you are doing, none of them should work. Browsers are built to specifically prevent cross-domain xhr.
Offline
Unless I'm not understanding what you are doing, none of them should work. Browsers are built to specifically prevent cross-domain xhr.
The code runs under a Vista gadget, which I guess doesn't have any issues doing it because the requests are successful.
Offline
Perhaps it's a scoping issue?
I'm not an expert on scope in JavaScript, but I'd be fearful of the references into req within the onreadystatechange function.
You were right, it was a scope/close issue.
The value of i in the onreadystate function was not what I was expecting.
By closing it, it worked like a charm:
var req=new Array(3);
var url=new Array(3);
url[0]="http://www.google.com";
url[1]="http://www.3.com";
url[2]="http://www.1.com";
function validate() {
for(var i=0; i<3; i++) {
req[i] = new XMLHttpRequest();
req[i].onreadystatechange = function(index) {
return function() {
if(req[index].readyState == 4 && req[index].status == 200) {
URL = url[index];
success();
}
};
}(i);
req[i].open("GET", url[i], true);
req[i].send(null);
}
}Offline
Pages: 1