javascript - *在* JSON 完成后返回数组?

标签 javascript jquery ajax

如何让这个函数在完成推送所有标记后返回整个数组?

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/

相关文章:

javascript - ''Required"功能似乎无法与返回确认一起使用

javascript - 是否可以为凸起按钮添加自定义悬停颜色?

javascript - ng-click - 单击后执行功能并重定向

javascript - jQuery .load 和 .resize 不能正常工作

php - 使用 AJAX 从 <select> 下拉列表中检索值?

javascript - jQuery post 大文本数据传输(最终加载)

asp.net - 将 jQuery AJAX 与 .NET 集成

javascript - FullCalendar - 更改 View 不工作

javascript - 如何避免在这种情况下修改事件对象

javascript - 使用 jQuery 或 Javascript 添加 <span> 标签?