Won't work that way. For the readystatechange function to be registered successfully, it doesn't look like it can be assigned to a variable because then the httprequest variable would have to be global. That can't be done because to avoid a race condition (I'm retrieving a bunch of requests, one after another, and therefore must do it syncronously, not async) the httprequest var must be local. In any case, I've tried to put the var declaration you wrote out in a variety of places, and the httprequest seems to always be undefined, even if I put it in the middle of the higher level function, right after httpRequest = new XMLHttpRequest();
So, Twey, I just solved it a different way, thanks to you triggering something in my thinking while on my way to get lo mein takeout. This whole exercise points out that the function assigned to the readystatechange is practically useless for anything else - all coding involving variable assignment must be done outside this function. The possible exception would be DOM assignments. I have this working to trim an array of links depending on whether or not the files exist:
Code:
for (m=imagetotl-1;m>=3;m--) {
nB = testExists(imagelink[m]);
if(nB) {
imagetotl--;
for (n=m;n<=imagetotl+1;n++) {
imagelink[n]=imagelink[n+1];
}
}
}
And the file test function is:
Code:
function testExists(imagepath) {
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml');
// See note below about this line
}
}
else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Oops, major XMLHTTP error');
return false;
}
httpRequest.onreadystatechange = function() { imagexists(httpRequest); };
httpRequest.open("HEAD", imagepath, false);
httpRequest.send(null);
if(httpRequest.status == 200) {
return nB=0;
} else {
return nB=1;
}
}
The object open is set to 'false' instead of the usual AJAX 'true' because I must wait until I get a response back from the server, otherwise the requests get mixed up because the browser will fire off another request before the server responds with the status of the current request. I have to test the request status here because I can't pass it from the function below as a variable anymore.
And, finally the important function to register the onreadystatechange property of the request object, but is not useful for assigning variables based on the request object status :
Code:
function imagexists(httpRequest) {}
I hope this helps someone else to do the same kind of things that I have to do.....
BTW, the Mozilla man page on this at http://developer.mozilla.org/en/AJAX/Getting_Started
doesn't mention this and implies that you can do what you can't do.
Bookmarks