$.getJSON return 值到变量

$.getJSON return value to variable

这是我的问题

我有一个充满国家代码的 JSON 文件,以及一个获取随机国家代码的函数,如下所示:

function getRandomCountryCode(specificMap){
  $.getJSON('../maps/' + specificMap + '.json', function( data ) {
    var countries = [];
    for (var i in data.country) {
      countries.push(data.country[i].code);
    }
    var rndCountryCode = countries[Math.floor(Math.random()*countries.length)];
    return rndCountryCode;
  });
};

在另一个函数中,我调用了上面的函数并尝试将 rndCountryCode 变量存储到另一个变量中,以便它在新函数中可用。

function loadMap(map){
  var specificMap = map;
  var y = getRandomCountryCode(specificMap);
  console.log("Y is : " + y);
}

我得到的只有undefined。我做了很多研究 (here and here and especially here) 并意识到这是因为 $.getJSON 的异步性质,我应该使用回调,但我无法弄清楚。

感谢您的帮助。

将你要执行的代码放在

之后
var y = getRandomCountryCode(specificMap);

成功回调中

function getRandomCountryCode(specificMap){
  $.getJSON('../maps/' + specificMap + '.json', function( data ) {
    var countries = [];
    for (var i in data.country) {
      countries.push(data.country[i].code);
    }
    var rndCountryCode = countries[Math.floor(Math.random()*countries.length)];
    >>>console.log("rndCountryCode  is : " + rndCountryCode );
    return rndCountryCode;
  });
};

由于 getJSON 是异步的,并且您不知道响应何时返回,因此保证处理响应的代码有效的唯一方法是将其放入成功处理程序(getJSON 的第二个参数)中。

无论花费多长时间,只要有成功响应,就会执行成功处理程序。