gpt4 book ai didi

javascript - 如何获取地理位置然后自动提交表单而无需单击按钮

转载 作者:行者123 更新时间:2023-11-30 14:03:44 25 4
gpt4 key购买 nike

我想调用一个页面来获取地理定位,然后自动将表单提交到我的 php 页面到 $_REQUEST getlatgetlon 而无需单击一个提交按钮。这是我所拥有的。在我的浏览器检查器中,我看到了我的地理位置值,但它不会自动提交。我尝试在我的 body 标记中使用 onload 函数,但后来发现您一次只能调用一个函数,而且我还读到这是一种不好的做法。我查看了另一个类似的问题,但无法拼凑起来。感谢您的帮助

<html>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
showPosition,
positionError
);
}
}

function showPosition(position) {
document.getElementById('getlat').value = position.coords.latitude;
document.getElementById('getlon').value = position.coords.longitude;
lon = document.getElementById('getlon').value;
lat = document.getElementById('getlat').value;
}

function positionError(error) {
if (error.PERMISSION_DENIED) alert('Please accept geolocation');
hideLoadingDiv();
showError(
'Geolocation is not enabled. Please enable to use this feature'
);
}
</script>

<script>
function PageLoad() {
getLocation();
document.frm1.submit();
}
</script>

<body>
<script>
window.onload = PageLoad();
</script>

<form action="results.php" name="frm1">
<input type="hidden" name="longitude" id="getlon" />
<input type="hidden" name="latitude" id="getlat" />
</form>
</body>
</html>

最佳答案

你一定没有意识到 javascript 的异步特性,否则这是一个非常简单的问题。无论如何,我在这里解释

当页面加载并找到 window.onload=PageLoad(); 时,它会调用 PageLoad() 函数,然后

function PageLoad() {
getLocation(); // <-- gets called
document.frm1.submit(); // <-- doesn't wait for getLocation() to complete;
// rather runs right away
}

正如您所猜到的,当 getLocation() 正在执行它的工作(在某种“线程”A 中)时,document.frm1.submit(); 开始运行(在另一个类似“线程”B) 并提交不是您期望的表单。

所以您需要做的是将与提交相关的代码移动到 showPosition() 中,以便一旦浏览器获取位置然后提交表单。

function showPosition(position) {
document.getElementById("getlat").value = position.coords.latitude;
document.getElementById("getlon").value = position.coords.longitude;
lon=document.getElementById("getlon").value;
lat=document.getElementById("getlat").value;
document.frm1.submit(); <-- submits when browser gets the users location
}

关于javascript - 如何获取地理位置然后自动提交表单而无需单击按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55853519/

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