Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest.open() exception handling

I have the following piece of code (only relevant parts):

xhttp=new XMLHttpRequest();
xhttp.open("GET",doc_name,false);
xhttp.send();
xmlDoc=xhttp.responseXML;
if(xmlDoc==null)
{
   xmlDoc=loadXMLDoc(defaultXml);
}

This runs fine as I load a default xml file if the specified file does not exist but shows a 404 error only in the console if the file does not exist. (This error does not reflect anywhere in the page except the console).

My question is that how should I check for this exception & is it necessary to add an extra piece of code for checking the existence of the file when the code runs without it?

like image 918
gopi1410 Avatar asked May 15 '12 08:05

gopi1410


1 Answers

You can access the HTTP response code via xhttp.status; either a 200 (OK) or 304 (Not Modified) would normally be considered a successful request.

xhttp=new XMLHttpRequest();
xhttp.open("GET",doc_name,false);
xhttp.send();

if (xhttp.status === 200 || xhttp.status === 304) {
    xmlDoc=xhttp.responseXML;
    if(xmlDoc==null)
    {
       xmlDoc=loadXMLDoc(defaultXml);
    }
}

Make sure you're declaring your variables first using var, otherwise you'll have implicit globals, which are bad.

Also make sure you have a good reason for doing this synchronously; synchronous XHR's lock up the browser whilst the request is pending. Making it async is highly recommended.

For the second part of your question, there's no problem what-so-ever; as long as your app can handle the exception. (which is seems to do)

like image 193
Matt Avatar answered Nov 07 '22 06:11

Matt