简体   繁体   English

从JavaScript函数访问返回值会导致HTML页面重新加载

[英]Accessing Returned Values From JavaScript Function Causes HTML Page to Reload

When the form is submitted the function buttonClicked() is run. 提交表单后,将运行buttonClicked()函数。 This function runs callGeoCode() which gets the latitude and longitude information for whatever the user typed in the form. 此函数运行callGeoCode(),该函数获取用户在表单中键入的内容的纬度和经度信息。 Whenever I click the button to submit the form the page reloads. 每当我单击按钮提交表单时,页面就会重新加载。 However when I comment out the console.log(location.lat+','+location.lng); 但是,当我注释掉console.log(location.lat+','+location.lng); line the page doesn't reload. 行页面不会重新加载。 Why would this be? 为什么会这样呢? I can't seem to figure it out. 我似乎无法弄清楚。

$('#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';
            }
        }
    );
}

Try this:- 尝试这个:-

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

For geocode api you can try something like 对于地理编码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'); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM