如果你想在服务器端保持计数器是最新的,你应该使用 AJAX 来更新服务器数据库。
基于本教程,这里有一个简单的例子:
mydiv.phtml:
<?php $_GET['id']=isset($_GET['id'])?$_GET['id']:1; include 'count.php'; ?>
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
var clickerid = <?php echo $_GET['id'] ?>; //counter id allows easy implementation of other counters if desired
var clicks = <?php echo $clicks ?>;
var clickLock = false;
var maxClickRate = 1000; //maximum click rate in ms, so the server won't choke
//Browser Support Code
function count(){
if (clickLock) {
alert('you\'re clicking too fast!');
return;
}
clickLock=true;
setTimeout('clickLock=false;',maxClickRate);
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById('cc').innerHTML = ++clicks;
}
}
// Now pass clicks value to the
// server script.
var queryString = "?id=" + clickerid + "&update=true";
ajaxRequest.open("GET", "count.php" +
queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<div onclick='count()'>
<form name='myForm'>
<input type='button' value='clickOnDiv'/>
</form>
</div>
Clicks so far: <span id='cc'><?php echo $clicks; ?></span>
</body>
</html>
计数.php:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
if (!isset($_GET['update'])){
$stmt = $dbh->prepare('SELECT count
FROM clicks
WHERE id = :clickerid');
$stmt->bindValue(':clickerid', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$clicks = $result['count'];
} else {
$stmt = $dbh->prepare('UPDATE clicks
SET count = count + 1
WHERE id = :clickerid');
$stmt->bindValue(':clickerid', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
}
$dbh = null;
} catch (PDOException $e) {
print "PDO Exception.";
die();
}
?>
set_database.php:
<?php
try {
$dbh = new PDO('mysql:host=localhost', 'user', 'password');
$dbh->query('CREATE DATABASE test;');
$dbh->query('CREATE TABLE test.clicks (id INT KEY, count INT);');
$dbh->query('INSERT INTO test.clicks VALUES (1,0);');
$dbh = null;
} catch (PDOException $e) {
print "PDO Exception.";
die();
}
?>