为什么我不能在JSON请求之外访问数组?

时间:2014-04-14 23:47:42

标签: jquery json

This post帮助我理解原因,但它对解决方案有点简要。

The documentation提到了回调函数.done().fail().always(),但我已经尝试过.done()并且无法在外部获取变量电话。

以下是我的相关代码:

var countries = [];

$.getJSON("js/flags.json", function(data) {
    $(data.flags).each(function(i) {
        countries.push(data.flags[i]);
    });
    console.log(countries);    // returns a big ol array :)
});
console.log(countries);    // returns an empty array :(

我只想全局使用这个数组。我错过了什么?

1 个答案:

答案 0 :(得分:0)

u/Adi中提到的this post是在Ajax调用中,a意味着异步,当你尝试控制日志时,国家数组的Ajax调用尚未完成,因此数组为空

我要做的是将Ajax调用包装在函数中并将回调传递给该函数:

function someCallBackFunction(arr){
   console.log(arr)
}

function yourFunction(someCallBackFunction){
  $.getJSON("js/flags.json", function(data) {

    $(data.flags).each(function(i) {
        countries.push(data.flags[i]);
    });
    console.log(countries);

    someCallbackFunction(countries)
  });
}