这几天刚接触Ajax,写了一个非常简单的计数器。
客户端文件counter.htm用作模板,counter.php调用counter.htm模板。
当访问counter.php时,数据库记录ip、time,计数器加一。
XMLHttpRequest向counter_action.php发出请求,counter_action.php返回一个数字。
函数setTimeout()设置自动更新时间。
counter.htm清单
/p>
"http://www.w3.org/TR/html4/loose.dtd">
Ajax计数器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);
}
}
}
Ajax计数器
counter.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清单
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();
?>
欢迎大家阅读《Ajax计数器(PHP)_jquery》,跪求各位点评,若觉得好的话请收藏本文,by 搞代码
微信 赏一包辣条吧~
支付宝 赏一听可乐吧~