[英]How to validate the existence of a JSON file before load it with the XMLHttpRequest Javascript object?
我正在將JSON文件從相對本地路徑加載到基於Web的應用程序中。 為此,我使用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);
我的問題是,當我不能管理瀏覽器錯誤(網:: ERR_FILE_NOT_FOUND) myFyle.json
是找不到的。 我想加載標准.json
文件(例如, myStandardFile.json
)時,發生這種情況。
有人有這樣做的想法嗎?
提前致謝!
佩德羅
您可以使用xobj.status === 404
來檢測“找不到文件”。
當用戶嘗試訪問斷開或無效的鏈接時,網站托管服務器通常會生成“ 404 Not Found”網頁。
如果是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);
})
演示:
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); })
我希望這能幫到您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.