2010-05-09 111 views
2

以下是我的JavaScript代码片段。它没有按预期运行,请帮助我。XMLHttpRequest泄漏

<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 screenshot

有程序中的漏洞。请帮忙。

编辑:在Firebug控制台预期的结果应该是这样的: -

位置
门柱内侧....
内回调

/* 5秒后*/

内部位置
POST ...
inside callba CK

/*不断重复*/

+0

看看这里:http://jsfiddle.net/ayLs7/它没有调用你的特定的AJAX页面,它再现你的问题。我没有看到它产生了你所描述的问题,即使让它运行了一段时间。我怀疑这个问题不在XHR中,但可能在你的Javascript的其他领域。 – Ryley 2010-06-04 18:05:53

回答

0

可能不是问题,但我可以建议两个重构:

合并回调)你的两个条件(:

if ((req.readyState == 4) && (req.status == 200)) { 

并且你可以缩短你的setTimeout行到:

setTimeout(getCurrentLocation, 5000); 

为了解决这个问题,我可以让你从callback()中移除setTimeout(),并用它取代getCurrentLocation()的调用?所以你只有在回调运行时才写“回调成功”,没有别的。

setTimeout(getCurrentLocation, 5000); //called on body load 
+0

我做了你提到的改变。我也需要setTimeout里面的回调,因为我希望代码在循环中每5秒钟运行一次。行为仍然不如预期。就像它在萤火虫截图中所显示的一样,有时候这个贴子是瞬间出现的,有时它们根本不会出现。我想每5秒发一次POST。 – Raja 2010-05-09 00:53:30