Javascript两个函数一键执行,但在从第一个函数获取值之后



我需要帮助为地理位置和AJAX表单提交创建javascript逻辑。 我的网站上有一个搜索,附近有一个搜索按钮。这里的问题是我想通过 AJAX 提交关键字,但同时我想从用户那里获取地理位置并发送纬度和经度值以及表单,但当我按下搜索附近按钮时,两个函数同时执行(表单直接提交,浏览器提示用户允许位置,但表单提交时没有纬度和长值)。 因此,请帮助我实现逻辑,以便浏览器首先获取当前位置值,然后将它们与用户输入的关键字一起提交,我也想一键执行这些功能,但不能同时执行。 下面是我的js和form代码。 希望我清楚。 提前致谢

<form method="post" class="form-inline" onsubmit="download(this['searchQuery'].value, this['Latitude'].value)" id="simple-firm" action="#">
<div class="form-group">
<div id="divSample" class="hideClass">Latitude:
<input type="text" id="Latitude" name="Latitude" value="">
<br>
<br>Longitude:
<input type="text" id="Longitude" name="Longitude" value="">
<br>
<input type="text" id="Position1" name="Position1" value="Miami">
</div>
<input type="text" class="form-control search-term" placeholder="Keyword"  name="searchQuery" id="searchQuery"> 
<input onclick="showLocation();" type="submit" class="search-btn" value="Search" id="simple-submit-button">
</div>
</form>
JAvascript for geo location using google APIs:
function showLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
} else {
alert("Your browser or device doesn't support Geolocation");
}
}
// If we have a successful location update
var lat;
function onGeoSuccess(event) {
document.getElementById("Latitude").value = event.coords.latitude;
document.getElementById("Longitude").value = event.coords.longitude;
lat  = event.coords.latitude;
document.getElementById("Position1").value = event.coords.latitude + ", " + event.coords.longitude;
console.log(document.getElementById("Latitude").value);
}
// If something has gone wrong with the geolocation request
function onGeoError(event) {
alert("Error code " + event.code + ". " + event.message);
}

AJAX:

// AJAX for Simple Form
$("#simple-submit-button").click(submitform);
function handleResponse(responseObj) {
console.log("response is "+responseObj.status+" and "+responseObj.text);
if( responseObj.status == "ok" ) {
$("#response_element").html(responseObj.text).css("color","green");
} else {
$("#response_element").html(responseObj.text).css("color","red");
}
}

function submitform() {
var check = document.getElementById('Latitude').value;
if(check == ""){
alert('danger');
} else{
var where = $("#simple-firm").attr("action");
var fi = $("#simple-firm[name=Latitude]").val();
var fj = $("#simple-firm[name=Longitude]").val();
var gk = $("#simple-firm[name=searchQuery]").val();
var what = {Latitude: fi, Longitude: fj, searchQuery: gk, lat};
$.post( where, what, handleResponse, "json");
alert('success');
}
}

你应该从第一个函数调用第二个函数

相关内容

最新更新