小编典典

如何使用Ajax从文件加载JSON对象?

javascript

我正在使用JSON传输数据。

我需要在HTML页面中使用Ajax读取仅在脚本中包含一个JSON对象的文件吗?

我是否也需要jQuery,或者是否可以使用Ajax加载该JSON文件?

在不同的浏览器上是否有所不同?


阅读 283

收藏
2020-05-01

共1个答案

小编典典

您不需要任何库,香草javascript中的所有内容均可用,以获取json文件并进行解析:

function fetchJSONFile(path, callback) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                var data = JSON.parse(httpRequest.responseText);
                if (callback) callback(data);
            }
        }
    };
    httpRequest.open('GET', path);
    httpRequest.send(); 
}

// this requests the file and executes a callback with the parsed result once
//   it is available
fetchJSONFile('pathToFile.json', function(data){
    // do something with your data
    console.log(data);
});
2020-05-01