为初学者问题道歉。
我尝试使用this answer将JSON文件中的数据读入我的javascript。我已将答案中的代码直接粘贴到我的javascript顶部(显然更改了pathToFile.json
)。我不确定的是我应该做什么,以及#34;对你的数据做些什么"评论是。我只想让解析后的data
对象可用于我的其余代码,但对javascript来说是一个非常新的我不能真正理解回调函数的工作原理。我可以在运行时看到控制台中记录的JSON文件中的数据,但是我尝试做的每件事(毫无疑问都是愚蠢的)都是这样做的。'该函数没有工作 - 当我稍后尝试引用它时,我收到ReferenceError: data is not defined
消息。
以下是其他答案的代码:
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);
});
答案 0 :(得分:2)
那是因为数据被定义为onreadystatechange
范围内的局部变量和回调函数。假设您不想尝试jQuery或其他一些框架,您可以尝试将数据绑定到全局变量:
var app = (function(){
var 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
json = data;
});
return { getData : function()
{
if (json) return json;
else return false;//or show some msg that 'data is not loaded yet'
}};
})();
// you now have access to your data via:
app.getData(); // will either be false or contain the data
关于回调函数的问题,它是一个传递给fetchJSONFile的函数,一旦从httpRequest检索数据就会调用它。由于这是异步的,因此您无法控制何时调用回调函数 - 一旦请求以OK状态(给定您当前的实现)完成,它将被调用。所以"所做的一切都与你的数据有关。"是检索和解析数据后执行的内容(即回调函数的主体)。