2017-06-05 37 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'); 
} 
相关问题