2010-05-09 29 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