开发者

javascript - generate random alpha variable and repeatedly ping server with it

开发者 https://www.devze.com 2023-03-13 11:40 出处:网络
I need to track my users time on website 开发者_JAVA百科using javascript.My website is only one page long so something like piwik or google whatever is too heavy handed.How can I generate a random 12

I need to track my users time on website 开发者_JAVA百科using javascript. My website is only one page long so something like piwik or google whatever is too heavy handed. How can I generate a random 12 letter long id (for example "sEjhWixldIdy") when the user first connects and repeatedly ping "example.com/tracker.py?id=sEjhWixldIdy" every 1000 milliseconds or so. I know how to do the python end of it, but how to do the client side?

EDIT: is this possible without using jQuery?


function randomString( strLen ) {
  var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
  strLen = strLen ? strLen : 12;
  var r = '';
  for (var i=0; i<strLen; i++)
    r += chars[Math.floor(Math.random() * chars.length)];
  return r;
}

Ping using jQuery:

function ping() {
  var randomId = randomString();
  // it will be called every 1 second
  setInterval(function(){
    $.get('http://example.com/tracker.py?id=' + randomId);
  }, 1000);
}

And use it when page is loaded:

$(document).ready(function(){
  ping();
});


The easiest strategy to achieve this in vanilla JS is probably to add an image on the page (src = your Python file) and update it every second:

<html>
    ...
    <script type="text/javascript">
        var img = document.createElement("IMG"),
            trackerId = Math.random(); // replace Math.random() with another ID generator.

        img.style.display = "none";
        document.body.appendChild(img);

        setInterval(function() {
                img.src = "http://example.com/tracker.py?id=" + trackerId + "&cacheb=" + Math.random();
            }, 1000);
    </script>
</body>
</html>

Alternatively, you can use the XMLHttpRequest object (and do a POST to eliminate cache-related issues):

var oHttp = new XMLHttpRequest(),
    trackerId = Math.random(); // replace Math.random() with another ID generator.;

setInterval(function() {
        oHttp.open("post", "http://example.com/tracker.py", true);
        oHttp.send("id=" + trackerId);
    }, 1000);
0

精彩评论

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