jQuery异步ajax查询和返回值问题(范围,闭包)

时间:2022-07-08 13:32:28

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:

由于异步查询和变量范围问题,代码无法正常工作。我无法理解如何解决这个问题。使用async更改为$ .ajax方法:false - 不是选项。我知道关闭,但我如何在这里实现它 - 不知道。我在这里看到了关于js和jQuery异步问题中的闭包的所有主题 - 但仍然没有。请帮助。这是代码:

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
    });
}

Thanks.

谢谢。

2 个解决方案

#1


1  

Just move this code:

只需移动此代码:

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

Into the callback function (where your first alert is)

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

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.

问题是,使用异步请求,即使请求尚未完成,代码也将继续执行。因此,在执行匿名回调函数之前,您的标记变量未正确设置。

#2


0  

All your code that has to deal with markers has to be in your callback function. This line of code:

所有必须处理标记的代码都必须在回调函数中。这行代码:

alert(markers.length); // length 0  

is executed before the Ajax call returns (i.e. before the callback is executed).

在Ajax调用返回之前(即在执行回调之前)执行。


That means your code should look more like this:

这意味着您的代码看起来应该更像这样:

$.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

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

         // more with cluster here
     }
},'json');

If you set or change variables in an Ajax callback, don't rely on their values outside of the callback.

如果在Ajax回调中设置或更改变量,请不要依赖回调之外的值。

#1


1  

Just move this code:

只需移动此代码:

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

Into the callback function (where your first alert is)

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

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.

问题是,使用异步请求,即使请求尚未完成,代码也将继续执行。因此,在执行匿名回调函数之前,您的标记变量未正确设置。

#2


0  

All your code that has to deal with markers has to be in your callback function. This line of code:

所有必须处理标记的代码都必须在回调函数中。这行代码:

alert(markers.length); // length 0  

is executed before the Ajax call returns (i.e. before the callback is executed).

在Ajax调用返回之前(即在执行回调之前)执行。


That means your code should look more like this:

这意味着您的代码看起来应该更像这样:

$.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

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

         // more with cluster here
     }
},'json');

If you set or change variables in an Ajax callback, don't rely on their values outside of the callback.

如果在Ajax回调中设置或更改变量,请不要依赖回调之外的值。