Reputation: 25
I am working loading a JSON file from a relative local path into my web based app. To do this I am using an XMLHttpRequest object, as following:
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'myFyle.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(JSON.parse(xobj.responseText));
}
}
xobj.send(null);
My issue is that I can't manage the browser error (net::ERR_FILE_NOT_FOUND) when myFyle.json
is not found. I would like to load an standard .json
file (e.g. myStandardFile.json
) when this happens.
Does anybody has an idea to do this?
Thanks in advance!
Pedro.
Upvotes: 0
Views: 523
Reputation: 10460
You can use xobj.status === 404
to detect 'file not found'.
The web site hosting server will typically generate a "404 Not Found" web page when a user attempts to follow a broken or dead link;
In case of 404 you can load your default file like this:
function load(file, callback) {
var defaultFile = "myStandardFile.json";
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', file, true);
xobj.onreadystatechange = function() {
if (xobj.readyState !== 4) return true;
if (xobj.status === 200) {
callback(JSON.parse(xobj.responseText));
//File not found.
//The second condition just to prevent endless calls
//in case if your default file doesn't exist
} else if (xobj.status === 404 && file !== defaultFile) {
load(defaultFile, callback);
}
}
xobj.send(null);
}
load("myFyle.json", function(data) {
console.log(data);
})
Demo:
function load(file, callback) {
var defaultFile = "https://httpbin.org/user-agent";
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', file, true);
xobj.onreadystatechange = function() {
if (xobj.readyState !== 4) return true;
if (xobj.status === 200) {
callback(JSON.parse(xobj.responseText));
//File not found
} else if (xobj.status === 404 && file !== defaultFile) {
load(defaultFile, callback);
}
}
xobj.send(null);
}
load("https://httpbin.org/inexistentFile.json", function(data) {
console.log(data);
})
I hope this will help you.
Upvotes: 1