gpt4 book ai didi

提交按钮上的 Javascript 函数 - 等待它完成

转载 作者:行者123 更新时间:2023-12-02 19:14:58 25 4
gpt4 key购买 nike

我想在按下表单上的提交按钮时触发一个函数,并等待javascript函数完成,然后继续表单提交。我不希望在 javascript 函数完成之前提交表单。**

这就是我现在所拥有的: http://jsfiddle.net/njDvn/68/

function autosuggest() {
var input = document.getElementById('location');
var options = {
types: [],
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
}

<!-- Get lat / long -->
function getLatLng() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('location').value;
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}

<!-- Load it -->
window.onload = autosuggest;

最佳答案

您可以拦截表单提交、中止它并向 Google 发送地理编码请求。

当服务器响应时,您可以从回调中重新提交表单(或者在失败时显示错误)。

将请求的状态存储在某处(为了简单起见,我在示例中使用了全局变量)。在这种情况下,它只是一个标志,指示地理编码请求是否成功完成(这样,当提交表单并重新触发监听器时,它将知道不要重新发送地理编码请求)。

http://jsfiddle.net/njDvn/75/

随意删除控制台日志记录。

您可能还想隐藏纬度/经度字段。

var GeoCoded = {done: false}; // this holds the status of the geo-coding request

$(document).ready(function(){
autosuggest(); // place your auto-suggest (now called autocomplete) box

$('#myform').on('submit',function(e){

if(GeoCoded.done)
return true;

e.preventDefault();
console.log('submit stopped');
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('location').value;

// disable the submit button
$('#myform input[type="submit"]').attr('disabled',true);

// send the request
geocoder.geocode({
'address': address
},
function (results, status) {
// update the status on success
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
// if you only want to submit in the event of successful
// geocoding, you can only trigger submission here.
GeoCoded.done = true; // this will prevent an infinite loop
$('#myform').submit();
} else { // failure
console.log("Geocode was not successful for the following reason: " + status);
//enable the submit button
$('#myform input[type="submit"]').attr('disabled',false);
}


});

});

});

关于提交按钮上的 Javascript 函数 - 等待它完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13214490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com