微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

变量被Ajax响应覆盖

如何解决变量被Ajax响应覆盖

我正在使用Google Maps和Geocoder遍历一个地址对象,返回它们的LatLng地址,并使用下面的setMarker函数中的原始详细信息和latlng地址创建标记

问题是response[a]被对象中的最后一个地址覆盖,因为for循环在返回AJAX结果之前运行。

如何保存当前循环中的response[a]中的数据,以便以后调用setMarker()时,其中包含正确的信息?

谢谢

          var limit = 0;

          for (a in response){

            if(limit<5){ // limit API calls

                  var addr = [response[a].Addr1,response[a].City,response[a].Zip];

                  geo = new google.maps.Geocoder();
                  geo.geocode({
                    address: addr.join(","),componentRestrictions: {
                    //  country: 'UK'
                    }
                  },function (results,status) {

                    if (status == google.maps.GeocoderStatus.OK && results) {

                        var latitude = results[0].geometry.location.lat();
                        var longitude = results[0].geometry.location.lng();
                        var latlng = new google.maps.LatLng(latitude,longitude);

                        if(latitude!="" && longitude!=""){

                            bounds.extend(latlng);
                            map.fitBounds(bounds);
                            _this.setMarker(map,limit,latlng,response[a]);

                        }

                    } // if geo results

              });

            }

            limit++;

          }

解决方法

您面临的问题是一个经典的问题,可以使用闭包函数来解决。

当前代码如下:

var a[20];

for(i=0;i<20;i++) {
    some_async_method() {
        //code that uses 'a[i]'
    }
}

使用闭包在异步函数中保留var a的范围:

var a[20];

for(i=0;i<20;i++) {
    (function(_a){
        some_async_method() {
            //code that uses 'a[i]' as '_a'
        }   
    })(a[i]);// self calling function that preserves the scope of a[i]
}

因此您的代码将如下所示:

var limit = 0;

for (a in response){

if(limit<5){ // limit API calls

      var addr = [response[a].Addr1,response[a].City,response[a].Zip];

      geo = new google.maps.Geocoder();
      (function(response_a){ // closure function to preserve scope of 'response[a]' 
          geo.geocode({
            address: addr.join(","),componentRestrictions: {
            //  country: 'UK'
            }
          },function (results,status) {

            if (status == google.maps.GeocoderStatus.OK && results) {

                var latitude = results[0].geometry.location.lat();
                var longitude = results[0].geometry.location.lng();
                var latlng = new google.maps.LatLng(latitude,longitude);

                if(latitude!="" && longitude!=""){

                    bounds.extend(latlng);
                    map.fitBounds(bounds);
                    _this.setMarker(map,limit,latlng,response_a);

                }

            } // if geo results

      });
    })(response[a]);

}

limit++;

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。