从getJSON请求返回数据,并在另一个函数中使用循环

时间:2014-11-29 22:41:55

标签: javascript jquery ajax for-loop getjson

我遇到了一个看似简单的问题。我从外部JSON文件中提取数据,需要遍历所有对象并返回其值以在另一个函数中使用。这是我到目前为止所拥有的......

var geo;

function getCountry(){

  $.getJSON('country.json', function(res) {
      $.each(res, function(key, val) {
          for(var i = 0; i < val.length; i++) {
              geo = val[i].geometry.coordinates;
              return geo;
          }
      })    
  });
}

function mapIt() {

    getCountry();

    $(".container").mapael({
        map : {
            name : "world_countries", // name of JS file
        },
        plots: {
        'Random': {
            latitude: geo[0],
            longitude: geo[1]
        }               
    }
    });
}

mapIt();

基本上,我使用第一个函数获取特定国家/地区的纬度和经度并尝试返回值(geo,这是一个包含lat / long的数组)并在第二个函数中使用它。我以为我可以在mapIt函数中调用getCountry函数,它会存储变量。

非常感谢任何建议/帮助,非常感谢!

编辑: 以下是一些JSON:

 {
 "world": [
  {
  "properties": {
    "sr_subunit": "Zimbabwe",
    "sr_brk_a3": "ZWE",
    "countries": "ZW",
    "scalerank": 0
  },
  "geometry": {
    "type": "Point",
    "coordinates": [
      29.851884620879,
      -19.002536710201
    ]
  }
},
{
 "properties": {
   "sr_subunit": "Samoa",
   "sr_brk_a3": "WSM",
   "countries": "WS",
   "scalerank": 0
 },
 "geometry": {
   "type": "Point",
   "coordinates": [
     -172.404145,
     -13.631557
   ]
  }
 }
]
}

1 个答案:

答案 0 :(得分:0)

这里的问题是你似乎不明白异步是如何工作的。 getCountry()来电之后的代码会在您getJSON回调之前很长时间内运行,因此它使用geoundefined。当你的JSON有多对坐标并且你只是试图实际使用它时,我真的不明白你想要做什么,但是这里你是如何操作第一对的:

function getCountry(){
  $.getJSON('country.json', function(res) {
      var country = res.world[0],
          coords;
      if (country) {
          coords = country.geometry.coordinates;
          mapCoordinates(coords[0], coords[1]);
      }
  });
}

function mapCoordinates(lat, long) {
    $(".container").mapael({
        map : {
            name : "world_countries", // name of JS file
        },
        plots: {
            'Random': {
                latitude: lat,
                longitude: long
            }               
        }
    });
}

function mapIt() {
    getCountry();
}

mapIt();