为什么我的 test_loc.php 会自动重新加载
why is my test_loc.php reloading by itself
我尝试获取地理位置坐标并在页面加载时将它们发送到 url
。
我在javascript中使用了onload
函数。当我 运行 js 它工作但它反复刷新自己。
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
window.onload = getLocation;
function showPosition(position) {
window.location.href = "test_loc.php?latitude=" + position.coords.latitude +
"&longitude=" + position.coords.longitude;
}
</script>
重新加载由以下行触发,它附加了异步调用的 latitude
和 longitude
因为:
window.location.href = "test_loc.php?latitude=" + position.coords.latitude + "&longitude=" + position.coords.longitude;
你可以做的是,你可以检查参数是否存在,你可以停止回调。请看这个:How to get the value from the GET parameters?
根据另一个问题的答案,你可以实现类似的东西:
function showPosition(position) {
if (typeof parse_query_string("latitude") == "undefined")
window.location.href = "test_loc.php?latitude=" + position.coords.latitude + "&longitude=" + position.coords.longitude;
}
因为您将 showPosition
作为成功回调传递给 geolocation.getCurrentPosition
,然后设置 location.href
以重新加载页面。
每次加载页面时,您都会通过 "onload" 事件调用 getLocation(),该事件又会调用 getCurrentPosition(),后者又会使用 window.location.href 重新加载页面。然后,当页面重新加载时,onload 事件再次触发,整个过程再次从头开始。
您基本上已经创建了一个无限循环。
难道为了传递坐标真的需要刷新页面吗?如果您需要将它们发送到服务器,请考虑使用 AJAX。
我尝试获取地理位置坐标并在页面加载时将它们发送到 url
。
我在javascript中使用了onload
函数。当我 运行 js 它工作但它反复刷新自己。
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
window.onload = getLocation;
function showPosition(position) {
window.location.href = "test_loc.php?latitude=" + position.coords.latitude +
"&longitude=" + position.coords.longitude;
}
</script>
重新加载由以下行触发,它附加了异步调用的 latitude
和 longitude
因为:
window.location.href = "test_loc.php?latitude=" + position.coords.latitude + "&longitude=" + position.coords.longitude;
你可以做的是,你可以检查参数是否存在,你可以停止回调。请看这个:How to get the value from the GET parameters?
根据另一个问题的答案,你可以实现类似的东西:
function showPosition(position) {
if (typeof parse_query_string("latitude") == "undefined")
window.location.href = "test_loc.php?latitude=" + position.coords.latitude + "&longitude=" + position.coords.longitude;
}
因为您将 showPosition
作为成功回调传递给 geolocation.getCurrentPosition
,然后设置 location.href
以重新加载页面。
每次加载页面时,您都会通过 "onload" 事件调用 getLocation(),该事件又会调用 getCurrentPosition(),后者又会使用 window.location.href 重新加载页面。然后,当页面重新加载时,onload 事件再次触发,整个过程再次从头开始。
您基本上已经创建了一个无限循环。
难道为了传递坐标真的需要刷新页面吗?如果您需要将它们发送到服务器,请考虑使用 AJAX。