DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解 >> Ajax計數器(PHP)
Ajax計數器(PHP)
編輯: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();
?>

 

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved