我想找到当前位置的纬度和经度,并在单击按钮时将其打印在另一页上。 虽然我成功获取了纬度和经度,但无法在另一页上打印/重定向。
有人可以帮忙吗?请找到下面的代码:
<!DOCTYPE html>
<html>
<head>
<script>
<p id="demo"></p>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</head>
<body>
<h2 >Geo-Logical Application</h2><br>
<p>Click the button to get Longitude and Latitude for your current position.</p><br>
<form action="Listing.html">
<button type="submit" onclick="getLocation()">Submit</button>
</form>
</body>
</html>
我想将输出重定向到列表页面。 谢谢
最佳答案
- 使用
window.location
重定向到另一个页面& - 将
event
传递给getLocation
以停止默认提交:
修改如下:
function getLocation(event) {
event.preventDefault();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p){
showPosition(p);
//
window.location="Listing.html?lat="+p.coords.latitude+"&lgt="+p.coords.longitude;
});
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
HTML 变成:
<form action="Listing.html">
<button type="submit" onclick="getLocation(event)">Submit</button>
</form>
如果您的页面处理 GET 参数:
window.location="Listing.html?lat="+p.coords.latitude+"&lgt="+p.coords.longitude;
否则,使用sessionStorage
来拥有有状态应用程序:
sessionStorage.setItem('POS',JSON.stringify(position.coords))
并在 Listing.html
中,通过以下方式获取: JSON.parse (sessionStorage.getItem('POS'))
关于javascript - 无法重定向另一个页面中的输出(HTML、Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38817359/