所以我试图做一个类似于这样的增量器:http://www.usagain.com/但我显然缺少代码来让它工作。我还遗漏了什么?下面是我非常相似的代码:
<html>
<head>
<title>Recycle Counter</title>
<script language="javascript" src="../jquery1.6.js"></script>
<script type="text/javascript">
/*function rand(from, to)
{
return Math.floor(Math.random() * (to - from + 1) + from); // Generates random number
} rand(10000, 100000);*/
function addCommas(nStr) //http://www.mredkj.com/javascript/nfbasic.html -- Source
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /('d+)('d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
$(function() {
function updateNum(){
$('#counter').load('test.php');
}
setTimeout(updateNum, 1000);
}
</script>
<style type="text/css">
#counterContainer{color: blue;font-family:Comic Sans MS;font-size:20px;}
#counter{display:inline;}
</style>
</head>
<body onload="getNum()">
<div id="counterContainer">
Counter ::: <div id="counter"> </div>
</div>
</body>
</html>
PHP <?php
for(int $i = 0; $i < 100; $i++)
echo $i;
?>
我想我需要在某个时候写入文件,但我之前尝试过,遇到了麻烦。不过这次甚至不会显示计数。我能做些什么?
看起来你设计的代码只运行一次updateNum,所以你的数字应该在页面加载后1秒更新,之后就不更新了。
你会想看看setInterval,它可以每X秒调用一个函数,它应该为你做的伎俩。
你可能想要考虑的一件事是优化。这是我要做的(作为一个例子)在你加载页面之前,在PHP中,取计数器在30-60秒内上升的平均数量,然后在javascript中,按这个数量更新计数器一段时间,也许是5分钟?5分钟后,再次运行ajax请求以获取计数器上升的最新平均值,并在接下来的5分钟内使用javascript更新计数器。
你可能会让服务器每秒调用一个计数器,特别是当很多人正在浏览这个网站的时候。