将javascript variabe升级到全球范围

时间:2019-02-03 08:31:45

标签: javascript jquery json scope

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

1 个答案:

答案 0 :(得分:0)

第一个示例中的问题是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>