下面是我的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显示非常奇怪的日志,比如同时发布的日志,间隔不定期。
下面是萤火虫的截图:
程序中有漏洞吗。请帮帮忙。
编辑: firebug控制台中的预期结果应该如下所示:
内部定位
邮寄..。
内部回调/* 5秒后*/
内部位置
邮寄..。
内部回调/*继续重复*/
发布于 2010-05-09 00:35:49
也许不是问题,但我可以建议两种重构:
在回调()中合并两个条件:
if ((req.readyState == 4) && (req.status == 200)) {
您可以将setTimeout行缩短为:
setTimeout(getCurrentLocation, 5000);
为了解决这个问题,我能让您从回调()中删除setTimeout()并用它替换对getCurrentLocation()的调用吗?因此,您只在运行回调时编写“回调成功”,而没有其他内容。
setTimeout(getCurrentLocation, 5000); //called on body load
https://stackoverflow.com/questions/2796164
复制相似问题