rlbailey
06-11-2007, 11:15 PM
Hi there,
I'm running off of a unix server and I need a javascript that is cross-browser to check if a file exists (image and html files). After experimentation, ActiveX just isn't playing nicely so I decided to go with XMLHTTP.
I need a synchronous XMLHTTP response that will work with IE, Mozilla. Problem there is that (i guess) Mozilla won't attach a .onreadystatechange event to a synchronous request, so my function always returns null (the anyonomous readystatechangefunction will never be called in Mozilla). The code works fine in IE though and I get the correct return values.
Any suggestions/help/advice?
HTTP.fileExists = function(url){
var request = HTTP.newRequest();
var exists = null;
//Register an event handler to revieve synchronous notification.
//This code says what to do with the response, and ti appears
//in a nested function here before we have even submitted the request.
request.onreadystatechange = function(){
//if the request is finished and was successful
if(request.readyState ==4){
if(request.status ==200 ){ exists = true; }
if( request.status == 404) { exists = false; /*this is file not found error*/ }
} else { /*alert("Request was not finished");*/ }
}
//Make a GET request for a given URL. The third arg of false specifies a synchronous request
request.open("HEAD", url, false);
//Now send the request. Since it is a GET request, we pass null for the body.
request.send(null);
return exists;
}
I'm running off of a unix server and I need a javascript that is cross-browser to check if a file exists (image and html files). After experimentation, ActiveX just isn't playing nicely so I decided to go with XMLHTTP.
I need a synchronous XMLHTTP response that will work with IE, Mozilla. Problem there is that (i guess) Mozilla won't attach a .onreadystatechange event to a synchronous request, so my function always returns null (the anyonomous readystatechangefunction will never be called in Mozilla). The code works fine in IE though and I get the correct return values.
Any suggestions/help/advice?
HTTP.fileExists = function(url){
var request = HTTP.newRequest();
var exists = null;
//Register an event handler to revieve synchronous notification.
//This code says what to do with the response, and ti appears
//in a nested function here before we have even submitted the request.
request.onreadystatechange = function(){
//if the request is finished and was successful
if(request.readyState ==4){
if(request.status ==200 ){ exists = true; }
if( request.status == 404) { exists = false; /*this is file not found error*/ }
} else { /*alert("Request was not finished");*/ }
}
//Make a GET request for a given URL. The third arg of false specifies a synchronous request
request.open("HEAD", url, false);
//Now send the request. Since it is a GET request, we pass null for the body.
request.send(null);
return exists;
}