如何让这个函数在完成推送所有标记后返回整个数组?
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;
}
最佳答案
你不能返回它,因为它是异步的(当响应返回时,它会在函数已经返回之后填充)。
但是您可以将它用于其他用途,例如:在它准备就绪/填充时将其传递给另一个函数,如下所示:
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);
});
}
关于javascript - *在* JSON 完成后返回数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3700275/