javascript - 无法将 JSON 文件放入变量中

标签 javascript json ajax xmlhttprequest

我正在尝试将 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/

相关文章:

java - Elasticsearch 扩展内部文档数组

json - 任何用于在 Classic ASP 中解析 JSON 的好库?

javascript - 如何简单地编写Ajax脚本(删除重复代码)?

javascript - 如何在ajax调用中单击按钮后刷新表格?

javascript - Codeigniter 日期选择器不工作

javascript Angularjs 从数组中获取单个值

javascript - 多个 Javascript 弹出窗口

javascript - json 不显示 php 查询的任何内容

javascript - 如何查询 Node.Js 的后端并更新页面而不重新加载 URL?

javascript - 使用 Moment.js 将 Unix 纪元时间转换为人类可读时间