jQuery的AJAX异步查询和返回值的问题(范围,封闭)返回值、范围、问题、jQuery

2023-09-11 00:45:23 作者:别念他べ

code不工作,因为异步查询,变量的作用域的问题。我不知道如何解决这个问题。更改为$就法异步:假的 - 不是一个选项。我知道闭包,但我怎么能在这里实现它 - 不知道。我见过的所有主题在这里关于JS和jQuery异步关闭的问题 - 但仍然一无所获。请帮助。 这里是code:

Code not working because of async query and variable scope problem. I can't understand how to solve this. Change to $.ajax method with async:false - not an option. I know about closures, but how I can implement it here - don't know. I've seen all topics here about closures in js and jQuery async problems - but still nothing. Help, please. Here is the code:

var map = null;
var marker;
var cluster = null;

function refreshMap() 
{
    var markers = [];  
    var markerImage = new google.maps.MarkerImage('/images/image-1_32_t.png', new google.maps.Size(32, 32));

    $.get('/get_users.php',{},function(data){
        if(data.status == 'error')
            return false;

        var users = data.users; // here users.length = 1 - this is ok;  
        for(var i in users)
        {
            //here I have every values from users - ok
            var latLng = new google.maps.LatLng(users[i].lat, users[i].lng);
            var mark = new google.maps.Marker({
                position: latLng,
                icon: markerImage
         });

             markers.push(mark);
             alert(markers.length); // length 1
        }

    },'json');

    alert(markers.length); // length 0  
    //if I have alert() above - I get result

    cluster = new MarkerClusterer(map, markers, 
    {
        maxZoom: null,
        gridSize: null
    });
}

感谢。

推荐答案

刚刚移动这个code:

Just move this code:

cluster = new MarkerClusterer(map, markers, 
{
    maxZoom: null,
    gridSize: null
});

进入回调函数(如果你的第一个警报)

Into the callback function (where your first alert is)

的问题是,与异步请求的code将继续执行,即使该请求还没有完成。所以,你的标记变量没有设置正确,直到你的匿名回调函数被执行。

The problem is that with an async request the code will continue to execute even though the request has not completed. So your markers variable isn't set properly until your anonymous callback function is executed.