Ajax计数器(PHP)

80酷酷网    80kuku.com

  ajax|计数器

这几天刚接触Ajax,写了一个非常简单的计数器。
客户端文件counter.htm用作模板,counter.php调用counter.htm模板。
当访问counter.php时,数据库记录ip、time,计数器加一。
XMLHttpRequest向counter_action.php发出请求,counter_action.php返回一个数字。
函数setTimeout()设置自动更新时间。

counter.htm清单

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Ajax计数器</title>
<style type="text/css">...
<!--
.style2 {...}{
    font-size: 16px;
    color: red;
}
-->
</style>
<script type="text/javascript">...
var xmlHttp;
function createXMLHttpRequest()
...{
    if (window.ActiveXObject)
    ...{
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    ...{
        xmlHttp = new XMLHttpRequest();
    }
}

function doCount()
...{
    createXMLHttpRequest();   
    var url = "counter_action.php";
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

function handleStateChange()
...{
    if(xmlHttp.readyState == 4)
    ...{
        if(xmlHttp.status == 200)
        ...{
            var counter = document.getElementById("counter");
            counter.innerHTML = xmlHttp.responseText+"次";
            setTimeout("doCount()",10000);
        }
    }
}
</script>
</head>
<body >
<p align="center" class="style2">Ajax计数器</p>
<table width="300" border="0" align="center">
  <tr>
    <td><div align="center" id ="counter"></div></td>
  </tr>
</table>
</body>
</html>
counter.php清单

<?php
include_once("./config/connect.php");
include_once("./private/functions.php");

$ip = getip(); //获取ip,函数定义在functions.php中
$time = time();

//访问数据库
$sql = "INSERT INTO `counter` VALUES (NULL,'$ip', '$time')";
$rs = $conn->Execute($sql);


//解析模板
$tpl->set_file("file","templates/counter.htm");
$tpl->parse("main","file");
$tpl->p("main");

$rs->Close();
$conn->Close();
?>
counter_action.php清单

<?php
include_once("./config/connect.php");
include_once("./private/functions.php");

//访问数据库
$sql = "SELECT * FROM `counter`";
$rs = $conn->Execute($sql);
$counter = $rs->rowcount();
$counter++;
echo $counter;

//释放数据库句柄
$rs->Close();
$conn->Close();
?>

 



分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: