我正在尝试将 JSON 文件的内容解析为名为 weatherArray
的变量。但是,该变量始终是一个空数组。
let weatherArray = [];
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
weatherArray = JSON.parse(this.responseText);
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
/* Expecting the value to be stored and be shown in console*/
console.log(weatherArray);
最佳答案
您正在检查结果,然后再返回。您需要移动该行:
console.log(weatherArray);
进入onreadystatechange
函数,该函数将在结果到达后检查结果。此外,您还需要调用 loadDoc()
函数(您可能就是这样做的)。
let weatherArray = [];
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
weatherArray = JSON.parse(this.responseText);
console.log(weatherArray);
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
loadDoc();
编辑如果您想在另一个函数中而不是在 onreadystatechange
内处理结果,您可以从 onreadystatechange
调用该函数。您可以使用全局 weatherArray
来做到这一点,但我只是建议在这种情况下简单地在参数中传递数据:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
showWeather(JSON.parse(this.responseText));
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
function showWeather(weatherArray) {
console.log(weatherArray);
}
loadDoc();
关于javascript - 无法将 JSON 文件放入变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49708914/