我正在使用 JSON 传输数据。
我的 HTML 页面需要什么才能使用 Ajax 读取一个只包含一个 JSON 对象的文件到我的脚本中?
我是否也需要 jQuery,或者是否可以使用 Ajax 加载该 JSON 文件?
不同浏览器有区别吗?
最佳答案
你不需要任何库,一切都可以在 vanilla 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);
});
关于javascript - 如何使用 ajax 从文件加载 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14388452/