2010-08-27 151 views
2

我對JavaScript函數調用changeMapLocation函數,其中我想返回變量latlong1。我在代碼中遇到了一些問題,以便在函數調用中返回這兩個變量並提醒。如何從JavaScript函數獲取多個返回值

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

回答

3

你在那裏有一個更大的問題。您正在調用異步$.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請求時,它將自行更改地圖位置。


另外請注意,您latlong1變量被封閉在success內部函數的範圍,不能從外部函數訪問。

+0

非常感謝您對代碼進行了更改,因爲您建議它的工作正常,再次感謝您的答覆。 – mahesh 2010-08-27 13:46:47

1

您只能返回一個值。該值可以是一個對象,但語法使用{}而不是()

而異步JavaScript和XML是異步。就調用函數而言,它是火和遺忘,你不會從它返回一個值。

你的回調必須完成任務,它不能將數據返回去完成它。

0

要返回多個值,您需要創建一個對象。

return({ 
    lat1: lat, 
    lat2: long1 
}); 

在那旁邊,這個代碼將無法工作,要麼因爲$.ajax()創建臺異步請求,後來觸發比你return statement呢。

所以你需要調用你自己的回調函數。像

function changeMapLocation(state, cb){ 
    $.ajax({ 
     // much data 
     success: function(longlatJson) { 
      // do a lot of things 
      if(typeof cb === 'function') 
       cb.apply(null, [lat, long1]); 
     } 
    }); 
} 

,然後調用它像

changeMapLocation("foobar", function(lat, long1){ 
    alert(lat); 
    alert(long1); 
}); 
+0

非常感謝您的答覆,但具有報警功能的問題是,它顯示警報,緯度和long1未定義 警報(「LAT」 + result.lat +「\ n」+「long:」+ result.long); – mahesh 2010-08-27 06:14:13

+0

@mahesh:如果你使用我在這裏建議的代碼,它將不會被定義(第二個例子,回調)。 – jAndy 2010-08-27 06:18:10

+0

非常感謝我對代碼進行了更改,因爲您建議它的工作正常再次感謝您的回答 – mahesh 2010-08-27 13:46:17

2

總結他們都在單一對象,並返回該對象:

var result = { 
    lat:lat, 
    long:long1 
} 

return result; 

然後,在你的函數調用:

var result = functionName(); 
alert("lat: " + result.lat + "\n" + "long: " + result.long); 
+0

非常感謝您的回覆,但警告功能的問題是它顯示警告與拉特ang long1 undefined alert(「lat:」+ result.lat +「\ n」+「long:」+ result.long); – mahesh 2010-08-27 06:13:39

1

或者稍長的版本就是有點更具可讀性

function getValues() 
{ 
    var r = {}; 
    r.lat = 22; 
    r.lat2 = 33; 

    return r; 
}; 


var x = getValues(); 
alert(x.lat); 
alert(x.lat2); 
0

正如在其他答案中指出的那樣,使用異步調用時,不會立即得到值您的Ajax調用,因爲Ajax調用不會完成。所以你得到的值是未定義的。你有兩個選擇:

選項1:

打動你使用Ajax的返回值放入Ajax調用成功回調函數來完成的操作。參見jAndy's或Daniel Vassallo的回答。

選項2:(異步:假)

您可以撥打電話要通過設置選項async: falseajax()功能同步。然後,這個方法會阻塞,直到收到響應,並且完成後,您將通過Ajax初始化值。

與第二個選項,您的代碼將是這樣的:

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

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

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

    $.ajax({ 
    url:googleUrl+address+sensor, 
    type:"POST", 
    async: false, 
    dataType:"json", 
    success:function(longlatJson) { 

     var jsonObj = JSON.parse(JSON.stringify(longlatJson)); 
     lat = jsonObj.results[0].geometry.location.lat; 
     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}; 

} 
+0

非常感謝您對代碼進行了更改,因爲您建議其再次正常工作,感謝您的答覆 – mahesh 2010-08-27 13:47:15