在jquery中动态构建数组后获取数组值的麻烦

时间:2014-12-19 15:53:48

标签: jquery multidimensional-array

这可能是我忽略的一件小事。我正在尝试在jquery中构建一个2D数组,然后在数组满后访问它。数组被填充,但后来数组似乎是空的。如何访问完整阵列?

var infoWindow = new google.maps.InfoWindow();
var map;
var names = [];

$(document).ready(function() {
...
});

function createMarker(marker_id, point,street, neighborhood, date,map, infowindow, causeParam) {
            $.post('php/get_data.php', {marker_id:marker_id},
                 function(data){

                     obj = jQuery.parseJSON(data);

                 for (var j=0; j < obj.length; j++) {

                     names.push([marker_id,objVictimdata[j].lastname]);


                 }//end for

                var marker = new google.maps.Marker({
                  id: marker_id,
                  position: point,
                  map: map,
                  icon: {
                    path: fontawesome.markers.MAP_MARKER,
                    scale: 0.5,
                    strokeWeight: 0.2,
                    strokeColor: 'black',
                    strokeOpacity: 1,
                    fillColor: '#000000',
                    fillOpacity: 0.7
                  }
                });

               google.maps.event.addListener(marker, "click", function() {
                    infoWindow.setContent('<div class="scrollFix">'+markerhtml+'</div>'); //markerhtml not included in this example
                    infoWindow.open(map, marker);
                });

                google.maps.event.addListener(map, "click", function(event) {
                    infoWindow.close();
                });

                console.log(names.length); //returns a higher number each time the loop iterates

        })//end post
        console.log(names.length); //returns 0!

};//end create marker

循环后为什么返回0?如何访问完整阵列?

1 个答案:

答案 0 :(得分:2)

它是一个异步函数(当你的请求仍处理时你的日志语句被命中,因此null数据),你需要使用回调函数:

function createMarker(marker_id, point,street, neighborhood, date,map, infowindow, causeParam, callback) {
    $.post('php/get_data.php', {marker_id:marker_id}, function(data) {
       ..
       ..
       callback(names)
    });
}

然后像这样使用回调:

createMarker(marker_id, point,street, neighborhood, date,map, infowindow, causeParam, function(names) {
    console.log(names);
});