jQuery异步ajax查询和返回值问题(作用域、闭包)

发布于 2024-09-03 05:06:04 字数 1191 浏览 2 评论 0原文

由于异步查询和变量范围问题,代码无法正常工作。我不明白如何解决这个问题。使用 async:false 更改为 $.ajax 方法 - 不是一个选项。我知道闭包,但我如何在这里实现它 - 不知道。我在这里看到了有关 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
    });
}

谢谢。

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

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

三寸金莲 2024-09-10 05:06:04

只需移动此代码:

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

进入回调函数(第一个警报所在的位置)

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

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.

娇俏 2024-09-10 05:06:04

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

alert(markers.length); // length 0  

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


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

$.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');

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

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


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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文