我需要使用javascript在网站上跟踪用户的时间。我的网站只有一页长,所以像piwik或谷歌的东西太重了。当用户第一次连接并且每1000毫秒左右重复ping“example.com/tracker.py?id=sEjhWixldIdy”时,如何生成随机12个字母长的id(例如“sEjhWixldIdy”)。我知道如何做python结束,但如何做客户端?
编辑: 这可能不使用jQuery吗?
答案 0 :(得分:3)
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;
}
使用jQuery Ping:
function ping() {
var randomId = randomString();
// it will be called every 1 second
setInterval(function(){
$.get('http://example.com/tracker.py?id=' + randomId);
}, 1000);
}
在加载页面时使用它:
$(document).ready(function(){
ping();
});
答案 1 :(得分:1)
在vanilla JS中实现这一目标的最简单策略可能是在页面上添加一个图像(src
=你的Python文件)并每秒更新一次:
<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>
或者,您可以使用XMLHttpRequest
对象(并执行POST
来消除与缓存相关的问题):
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);