簡體   English   中英

JSON解析的Javascript變量范圍

[英]Javascript variable scope for json parse

我正在使用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); } 

注意:以上代碼尚未經過測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM