jQuery的AJAX异步查询和返回值的问题(范围,封闭) [英] jQuery async ajax query and returning value problem (scope, closure)

查看:131
本文介绍了jQuery的AJAX异步查询和返回值的问题(范围,封闭)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于jQuery的AJAX异步查询和返回值的问题(范围,封闭)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆