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';
}
}
);
}
旁白:你不能这样做'无功位置= callGeoCode(userInput);'因为callGeoCode不返回任何内容。同样,'return {lat:lat,lng:lng};'将失败,因为回调函数没有提供任何代码的返回值。您应该使用ajax回调函数中来自ajax调用的数据填充结构。 – James
@James So,我将如何能够调用GeoCode返回值? –
使用异步函数不能很好地返回值。回调函数是接收数据的“做事情”的正确场所,也许在那里调用另一个函数并将它传递给你所收到的数据。看看[这个问题](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – James