2010-09-13 57 views
1

如何使这个函数返回整个数组完成推动所有标记?* JSON完成后返回数组* *

function XTW_getLocations(data, div_id, map) { 
    var markers = []; 
    var marker; 
    var latLngBounds = new google.maps.LatLngBounds(); 
    $(div_id).empty(); 
    $.getJSON('GetLocations', "country=" + data.id, 
     function(data){ 
      $.each(data, function(index, data) { 
       latLngBounds.extend(new google.maps.LatLng(data.location.latitude, data.location.longitude)); 
       $(div_id).append(new Option(data.name, data.id)); 
       marker = createMarker(data, icon, html, map); 
       markers.push(marker); 
      }); 
      map.fitBounds(latLngBounds); 
     }); 
    return markers; 
} 

回答

1

你不这样做,AJAX查询(getJSON)是异步也就是说,只要你发出你出处理的正常秩序的呼唤,你转而使用一个回调,就像你做调用getJSON时:

function XTW_getLocations(data, div_id, map, callBack) { 
    var markers = []; 
    var marker; 
    var latLngBounds = new google.maps.LatLngBounds(); 
    $(div_id).empty(); 
    $.getJSON('GetLocations', "country=" + data.id, 
     function(data){ 
      $.each(data, function(index, data) { 
       latLngBounds.extend(new google.maps.LatLng(data.location.latitude, data.location.longitude)); 
       $(div_id).append(new Option(data.name, data.id)); 
       marker = createMarker(data, icon, html, map); 
       markers.push(marker); 
      }); 
      map.fitBounds(latLngBounds); 
      callBack(markers); //Callback goes here 
     }); 
    //return markers; 
} 

现在,调用XTW_getLocations当你需要添加一个 回调你的电话:

XTW_getLocations({some:'data'},'#map','map.png',function(markers){ 
    //Handle markers here 
}) 
+0

而我可以在那里返回标记呢? – 2010-09-13 12:26:12

+0

不幸的是,没有......你永远无法将标记返回到任何地方,但是你可以处理回调中的数据,或者如果你想重用它,而不是匿名函数使用命名函数。 – 2010-09-13 12:35:12

+0

我很快尝试了它,并返回XTW_getLocations(x,x,x,function(markers){return markers;})* SEEMS *。但是,情况并非如此?这只是运气? – 2010-09-13 12:36:56

2

你不能返回它,因为它是异步的(当响应返回时,在函数已经返回后它会被填充)。

但是,您可以将它用于别的东西,例如:它传递给另一个函数当它准备/填充,比如:

function XTW_getLocations(data, div_id, map) { 
    var markers = []; 
    var marker; 
    var latLngBounds = new google.maps.LatLngBounds(); 
    $(div_id).empty(); 
    $.getJSON('GetLocations', "country=" + data.id, 
     function(data){ 
      $.each(data, function(index, data) { 
       latLngBounds.extend(new google.maps.LatLng(data.location.latitude, data.location.longitude)); 
       $(div_id).append(new Option(data.name, data.id)); 
       marker = createMarker(data, icon, html, map); 
       markers.push(marker); 
      }); 
      anotherFunction(markers); 
      map.fitBounds(latLngBounds); 
     }); 
} 
+0

所以通过让它内部getJSON()和each()之后anotherFunction()将不会被调用,直到each()完成? – 2010-09-13 12:22:23

+0

但是,如何让它回到第一个称为XTW_getLocations的变种..? – 2010-09-13 12:24:06

+0

@ M.E - 更正第一条评论,第二条评论:您不需要,只要有需要,您就可以将数据传递到其他地方。您可以将回调函数传递给'XTW_getLocations',或者将其传递给内部的相同函数,但不返回。唯一的方法是使其同步,从而锁定浏览器。 – 2010-09-13 12:26:12