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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With