這幾天剛接觸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();
?>