Processing XMLHttpRequest.open ()

I have the following code snippet (only relevant parts):

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

This works fine when I load the 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 is not reflected anywhere on the page except the console).

My question is, how should I check for this exception and do I need to add an additional piece of code to check for the existence of the file when the code works without it?

+5
source share
1 answer

You can get the HTTP response code through xhttp.status; either 200(OK) or 304(Not Modified) is usually considered successful.

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);
    }
}

, , var, , .

, ; XHR , . async .

, --; . (, , )

+4

All Articles