下面是我的 javascript 代码片段。它没有按预期运行,请帮我解决这个问题。
<script type="text/javascript">
function getCurrentLocation() {
console.log("inside location");
navigator.geolocation.getCurrentPosition(function(position) {
insert_coord(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
});
}
function insert_coord(loc) {
var request = new XMLHttpRequest();
request.open("POST","start.php",true);
request.onreadystatechange = function() {
callback(request);
};
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send("lat=" + encodeURIComponent(loc.lat()) + "&lng=" + encodeURIComponent(loc.lng()));
return request;
}
function callback(req) {
console.log("inside callback");
if(req.readyState == 4)
if(req.status == 200) {
document.getElementById("scratch").innerHTML = "callback success";
//window.setTimeout("getCurrentLocation()",5000);
setTimeout(getCurrentLocation,5000);
}
}
getCurrentLocation(); //called on body load
</script>
我想要实现的是每 5 秒左右将我的当前位置发送到 php 页面。我可以在我的数据库中看到很少的坐标,但过了一段时间它变得很奇怪。 Firebug 以不规则的间隔显示非常奇怪的日志,例如同步 POST。
这是 Firebug 屏幕截图:
程序中是否存在漏洞。请帮忙。
编辑:firebug 控制台中的预期结果应该是这样的:-
inside location
POST ....
inside callback/* 5 secs later */
inside location
POST ...
inside callback/* keep repeating */
最佳答案
可能不是问题,但我可以建议两个重构:
在 callback() 中合并你的两个条件:
if ((req.readyState == 4) && (req.status == 200)) {
并且您可以将 setTimeout 行缩短为:
setTimeout(getCurrentLocation, 5000);
为了解决这个问题,我可以让你从 callback() 中删除 setTimeout(),并用它替换对 getCurrentLocation() 的调用吗?所以你只在回调运行时写“回调成功”,没有别的。
setTimeout(getCurrentLocation, 5000); //called on body load
关于javascript - XMLHttpRequest 泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2796164/