【问题标题】:Level up javascript variabe to global scope [duplicate]将javascript变量升级到全局范围[重复]
【发布时间】:2019-06-27 07:24:48
【问题描述】:

我正在尝试在脚本中包含一个外部 JSON 文件:

var locations;

$.getJSON(themeUri + '/resources/location.json', function(result){
  locations = result;
  console.log(locations); // it shows right results.
});

console.log(locations); // undef

locations 不在全局范围内。正如我所读到的,这是因为异步功能。

所以,我尝试了:

var locations;

function jsonCallback(result){
  locations = result;
}

$.getJSON(themeUri + '/resources/location.json', jsonCallback);

也不行。如何将 JSON 内容放入全局变量中?

【问题讨论】:

  • getJson 是异步函数,这意味着您的解释器不等待 json 请求。位置变量在 JSON 请求完成后显示数据

标签: javascript jquery json scope


【解决方案1】:

您最初示例中的问题是console.log 发生在async 调用之前。

// 1. declaration happens
var locations;

// 3. this happens
$.getJSON(themeUri + '/resources/location.json', function(result){
  locations = result;
  console.log(locations); // it shows the right results.
});

// 2. console.log happens
console.log(locations); // undefined

所以2. 未定义是有道理的,因为回调尚未发生。

可能的解决方案:

var locations;

function fillLocations(responseJSON) {
  locations = responseJSON;
  console.log(locations); 
  // Continue to next operation…
}

$.getJSON( 'https://jsonplaceholder.typicode.com/todos/1', function(result){
  fillLocations(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

【讨论】:

  • 正如安迪在他的回答中已经提到的那样,您不能将控制台放在功能之外。在这种情况下,您将始终得到undefined。标记的重复问题中给出了可能的解决方案。
  • 好的,我正在阅读。它有很多信息。非常感谢!我想,我现在明白了。
  • 最后,这个答案解决了这个问题。感谢您的耐心。
猜你喜欢
  • 2014-09-17
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
  • 2015-09-30
  • 2015-08-07
  • 2018-09-02
  • 2012-07-17
  • 2013-01-24
相关资源
最近更新 更多