如何在使用 javascript 中的 XMLHttpRequest 从 json 文件读取后将响应存储到全局变量中并在程序的任何位置使用它

问题描述 投票:0回答:2

我有一个 Javascript 文件,我需要在其中使用 XMLHttpRequest 读取一个 json 文件并将响应存储到全局变量中,以便我可以在程序的其他地方使用它,但我不知道为什么响应没有存储到全局变量。任何人都可以告诉我为什么它没有被存储以及我可以实现它的方式。

这是我的代码

var xmlhttp = new XMLHttpRequest();
var url = './output.json';
var myArr;

xmlhttp.onreadystatechange = function () {
  if (this.readyState == 4 && this.status == 200) {
    let arr = JSON.parse(this.responseText);
    console.log(arr);
    myFunction(arr);
  }
};
xmlhttp.open('GET', url, true);
xmlhttp.send();

function myFunction(arr) {
  myArr = arr;
  console.log(myArr);
}

console.log(myArr);

最后一个控制台日志说未定义。

我期待最后一个控制台日志将 json 显示为数组。

javascript json xmlhttprequest global-variables
2个回答
0
投票

您可以通过直接将 api 响应分配给全局变量来以简单的方式做到这一点,就像这样:

    let myArr; // declare a global variable to store the response

    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'data.json', true);
    xhr.onload = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        myArr= JSON.parse(xhr.responseText); // assign the response to the global variable
      }
    };
    xhr.send();

    // You can use the myArr variable anywhere in your program now
    console.log(myArr);

0
投票

XMLHttpRequest
是一个异步操作。

所以当你在这个操作之外做一个

console.log
时,它在异步部分的异步部分之前执行。

为了和

myArr
一起工作,你应该留在
myFunction

© www.soinside.com 2019 - 2024. All rights reserved.