简体   繁体   中英

How to validate the existence of a JSON file before load it with the XMLHttpRequest Javascript object?

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 (eg myStandardFile.json ) when this happens.

Does anybody has an idea to do this?

Thanks in advance!

Pedro.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM