javascript - 如何从 JavaScript 函数中获取多个返回值

标签 javascript jquery html ajax dhtml

我有对 changeMapLocation 函数的 JavaScript 函数调用,我想在其中返回变量 latlong1。我在返回这两个变量并在函数调用中发出警报的代码中遇到了一些问题。

var sample = changeMapLocation(state);
alert(sample.lat1);
alert(sample.lat2); 

function changeMapLocation(state) {
   var addressval=state;
   var address;
   var url;
   var googleUrl= "http://maps.google.com/maps/api/geocode/json?";
   var  sensor  = "&sensor=false";

   if(addressval != null && addressval !="" && addressval.length!=0) {

      address = "address="+encodeURIComponent(addressval);

      $.ajax({
        url:googleUrl+address+sensor,
        type:"POST",
        dataType:"json",
        success:function(longlatJson) {
           var jsonObj = JSON.parse(JSON.stringify(longlatJson));
           var lat = jsonObj.results[0].geometry.location.lat;
           var long1 = jsonObj.results[0].geometry.location.lng;
           alert(lat);
           alert(long1);
           //var latlng = new google.maps.LatLng(lat,long1);
           //alert(latlng);
        },
        error:function(){alert("unable to conect to google server");}
      });
   }
   return(lat1:lat,lat2:long1); 
}

最佳答案

你那里有一个更大的问题。您正在调用异步 $.ajax()方法,它的回调函数将在您的 changeMapLocation() 函数返回后被调用,因此您的函数将不会像您期望的那样工作。按照以下示例中的注释进行操作:

function changeMapLocation(state) {
   var lat;
   var long1;
   // Since the $.ajax() method is using the asynchronous XMLHttpRequest, it 
   // will not block execution, and will return immediately after it is called,
   // without waiting for the server to respond.
   $.ajax({
      url: 'url-here',
      type: 'POST',
      success: function(longlatJson) {
         // The code here will be executed only when the server returns
         // a response to the ajax request. This may happen several 
         // milliseconds after $.ajax() is called.
         var jsonObj = JSON.parse(JSON.stringify(longlatJson));
         lat = jsonObj.results[0].geometry.location.lat;
         long1 = jsonObj.results[0].geometry.location.lng;
         // Now lat and long1 are set, but it is too late. Our 
         // changeMapLocation() function will have already returned.
      }
   });
   // This part will be reached before the server responds to the asynchronous
   // request above. Therefore the changeMapLocation() function returns an  
   // object with two properties lat1 and lat2 with an undefined value.
   return {lat1: lat, lat2: long1};
}

您应该考虑重构您的代码,使处理 ajax 响应的逻辑位于 success 回调中。示例:

function changeMapLocation(state) {
   $.ajax({
      url: 'url-here',
      type: 'POST',
      success: function(longlatJson) {
         var jsonObj = JSON.parse(JSON.stringify(longlatJson));
         var lat = jsonObj.results[0].geometry.location.lat;
         var long1 = jsonObj.results[0].geometry.location.lng;

         // Update your map location in here, or call a helper function that
         // can handle it:
         myGoogleMap.setCenter(new google.maps.LatLng(lat, long1));
      }
   });
}

请注意,changeMapLocation() 不再返回任何内容。当服务器响应 Ajax 请求时,它将自行更改 map 位置。


另外请注意,您的 latlong1 变量包含在 success 内部函数的范围内,无法访问来自外部函数。

关于javascript - 如何从 JavaScript 函数中获取多个返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3581687/

相关文章:

javascript - 停止 setInterval

javascript - 通过网络摄像头检测图像中的文本

html - 如何在文本列表之间放置垂直线?

html - 在 li 中卡住垂直文本对齐

javascript - JSfiddle 创建点击后消失的按钮

javascript - 如何让我的选项卡 100% 位于顶部?

javascript - 迭代 javascript 数据对象并查找平均值的最佳方法

javascript - 单击单选按钮时触发事件

javascript - 将字符串解析为 Javascript 中的原始值

javascript - 在 div 中制作两个独占复选框