首页 > 解决方案 > 将 javascript 变量升级到全局范围

问题描述

我正在尝试在脚本中包含一个外部 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 内容放入全局变量中?

标签: javascriptjqueryjsonscope

解决方案


您最初示例中的问题是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>


推荐阅读