简体   繁体   English

如何在使用XMLHttpRequest Javascript对象加载JSON文件之前验证其存在性?

[英]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. 我正在将JSON文件从相对本地路径加载到基于Web的应用程序中。 To do this I am using an XMLHttpRequest object, as following: 为此,我使用XMLHttpRequest对象,如下所示:

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. 我的问题是,当我不能管理浏览器错误(网:: ERR_FILE_NOT_FOUND) myFyle.json是找不到的。 I would like to load an standard .json file (eg myStandardFile.json ) when this happens. 我想加载标准.json文件(例如, myStandardFile.json )时,发生这种情况。

Does anybody has an idea to do this? 有人有这样做的想法吗?

Thanks in advance! 提前致谢!

Pedro. 佩德罗

You can use xobj.status === 404 to detect 'file not found'. 您可以使用xobj.status === 404来检测“找不到文件”。

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; 当用户尝试访问断开或无效的链接时,网站托管服务器通常会生成“ 404 Not Found”网页。

In case of 404 you can load your default file like this: 如果是404,您可以像这样加载默认文件:

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. 我希望这能帮到您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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