开发者

XMLHttpRequest leak

Below is my javascript code snippet. Its not running as expected, please help me with this.

<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开发者_如何学Python(getCurrentLocation,5000);
       }
   }

getCurrentLocation(); //called on body load
</script>

What i'm trying to achieve is to send my current location to the php page every 5 seconds or so. i can see few of the coordinates in my database but after sometime it gets weird. Firebug show very weird logs like simultaneous POST's at irregular intervals.

Here's the firebug screenshot:

XMLHttpRequest leak

IS there a leak in the program. please help.

EDIT: The expected outcome in the firebug console should be like this :-

inside location

POST ....

inside callback

/* 5 secs later */

inside location

POST ...

inside callback

/* keep repeating */


Probably not the problem, but I can suggest two refactorings:

Merge your two conditions in callback():

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

And you can shorten your setTimeout line to:

setTimeout(getCurrentLocation, 5000);

And in an effort to fix the problem, can I get you to remove the setTimeout() from callback(), and replace the call to getCurrentLocation() with it? So you're only writing "callback success" when the callback is run, nothing else.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜