用于 json parse 的 Javascript 变量范围

Javascript variable scope for json parse

本文关键字:变量 范围 Javascript json parse 用于      更新时间:2023-09-26

我正在使用来自http://www.kryptonite-dove.com/blog/load-json-file-locally-using-pure-javascript读取 JSON 文件并将其存储为变量。

代码工作正常;我的 json 对象成功打印到控制台。但是,我希望访问函数外部的变量。我将定义移到了外面,但这不起作用。我做错了什么?

function loadJSON(callback) {   
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = function () {
      if (xobj.readyState == 4 && xobj.status == "200") {
        // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
        callback(xobj.responseText);
      }
  };
  xobj.send(null);  
}

var actual_JSON; <--- I moved the definition outside here 
function init() {
  loadJSON(function(response) {
  // Parse JSON string into object
    actual_JSON = JSON.parse(response);  
    console.log(actual_JSON); ---> this works
 });
}
init();
console.log(actual_JSON);     ----> this doesn't work; I get the var is undefined 

loadJSON发出GET请求。您发送给它的callback函数在响应返回时执行,即在获取 JSON 时执行。

init();
console.log(actual_JSON);

因此,init()被调用并在内部执行 GET 请求,并且由于这是异步的,因此不会阻止其余代码的执行。所以下一行console.log(actual_JSON)执行,此时actual_JSON的值不会被修改。

你可以做这样的事情来让它更清楚一点:

function init() {
    loadJSON(function(response) {
        actual_JSON = JSON.parse(response);  
        consumeData(actual_JSON); //call another function with the actual JSON
    });
}
function consumeData(actualJson) {
    //write the rest of the code here
}

看看你的loadJSON你会发现它需要一个函数作为回调。 这样做是因为HTTP请求是异步发送的,由服务器和网络决定运行需要多长时间,同时页面上的其余JavaScript继续执行(例如,您的最终console.log)在设置变量之前。

当HTTP请求完成(onreadystatechange位)时,它将运行你传递给loadJSON的函数 - 这是你设置变量和工作console.log的函数。

你如何几个选项:

  1. 同步运行你的Ajax,这样它就不会执行JS的其余部分(坏主意)
  2. 为您正在执行的操作添加回调:

    var actual_JSON; <--- I moved the definition outside here 
    function init() {
      loadJSON(function(response) {
      // Parse JSON string into object
        actual_JSON = JSON.parse(response);
        exec_after_init();
     });
    }
    init();
    function exec_after_init {
       console.log(actual_JSON);
    } 
    

注意:上面的代码尚未经过测试