作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想调用一个页面来获取地理定位,然后自动将表单提交到我的 php 页面到 $_REQUEST
getlat
和 getlon
而无需单击一个提交按钮。这是我所拥有的。在我的浏览器检查器中,我看到了我的地理位置值,但它不会自动提交。我尝试在我的 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/
我是一名优秀的程序员,十分优秀!