2012-05-24 147 views
1

好吧,这是我的JS功能:异步调用

function GetLatLong() { 
    var geocoder = new google.maps.Geocoder(); 
    var address = $('#txtAddress').val() + ', ' + $('#txtCity').val() + ', ' + $find('drpState').get_text() + ', ' + $find('drpCountry').get_text(); 
    var result = false; 
    geocoder.geocode({ 'address': address }, function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var location = results[0].geometry.location; 
      $('#hiddenLatLong').val(location); 
      result = true; 
     } 
     else { 
      alert("Geocode was not successful for the following reason: " + status); 
      result = true; 
     } 
    }); 

    return result; 
} 

现在,我想是的,我想一旦我存储在隐藏字段中的值返回结果。这里发生的是,我在按钮单击时调用此函数,但因为调用是异步的,所以它在click上返回false,并且我无法在隐藏字段中获得结果值。有没有什么方法可以让我等待或在隐藏领域获得一些解决办法?

回答

1

地理编码函数中的第二个参数是一个回调函数,如果地理编码结果返回,则该函数将被调用。因此,从您提供的代码中,如果Google返回结果,则应设置隐藏值。

但是,您的GetLatLong()功能提前完成,因此返回false。所以你不应该让你的处理依赖于这个方法的返回值。