2017-06-05 38 views
0

當提交表單時,會運行函數buttonClicked()。該函數運行callGeoCode(),獲取用戶在窗體中輸入的任何內容的緯度和經度信息。每當我點擊按鈕提交表單頁面重新加載。但是,當我註釋掉console.log(location.lat+','+location.lng);行時,頁面不會重新加載。爲什麼會這樣?我似乎無法弄清楚。從JavaScript函數訪問返回值函數導致HTML頁面重新加載

$('#find-location').submit(function() { 
    buttonClicked(); 
    return false; 
});  
function buttonClicked() { 
    userInput = document.getElementById("locationInput").value; 
    var location = callGeoCode(userInput); 
    console.log(location.lat+','+location.lng); 
} 
function callGeoCode(userInput) { 
    $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + userInput + '&key=APIKEY-GOES-HERE', 
     function(data) { 
      if (data.status === 'OK') { 
       var lat = data.results[0].geometry.location.lat; 
       var lng = data.results[0].geometry.location.lng; 
       return {lat: lat, lng: lng}; 
      } else { 
       return 'FAILED'; 
      } 
     } 
    ); 
} 
+0

旁白:你不能這樣做'無功位置= callGeoCode(userInput);'因爲callGeoCode不返回任何內容。同樣,'return {lat:lat,lng:lng};'將失敗,因爲回調函數沒有提供任何代碼的返回值。您應該使用ajax回調函數中來自ajax調用的數據填充結構。 – James

+0

@James So,我將如何能夠調用GeoCode返回值? –

+0

使用異步函數不能很好地返回值。回調函數是接收數據的「做事情」的正確場所,也許在那裏調用另一個函數並將它傳遞給你所收到的數據。看看[這個問題](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – James

回答

0

試試這個: -

$('#find-location').submit(function (event) { 
    event.preventDefault(); 
    buttonClicked(); 
    return false; 
}); 

對於地理編碼的API,你可以嘗試這樣

function buttonClicked() { 
    userInput = document.getElementById("locationInput").value; 
    var locationPromise = callGeoCode(userInput); 
    locationPromise.done(function(data) { 
     console.log(data); 
     if (data.status === 'OK') { 
      var lat = data.results[0].geometry.location.lat; 
      var lng = data.results[0].geometry.location.lng; 
      console.log("lat:" + lat + "long:" + long); 
     } 
    } 
} 

function callGeoCode(userInput) { 
    return $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + userInput + '&key=APIKEY-GOES-HERE'); 
} 
相關問題