Ajax(Asynchronous JavaScript and XML)即異步的 JS 與 XML,是一組與服務器語言無關的技術,可用於 PHP、JSP、ASP.NET 等。其工作原理為:創建 Ajax 引擎 → 發送數據給服務器 → 通過回調函數接收數據 → 把數據賦給指定頁面元素。
下面以注冊驗證為例:register.php 為注冊頁面,registerProcess.php 負責接收並返回數據。
<script type="text/javascript">
function sendRequest(){
var xmlHttpRequest;
// 不同浏覽器獲取對象方式不同
if(window.ActiveXObject){
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}else{
xmlHttpRequest = new XMLHttpRequest();
}
return xmlHttpRequest;
}
var myXmlHttpRequest;
function checkName(){
myXmlHttpRequest = sendRequest();
if(myXmlHttpRequest){
// GET 方式提交,加時間戳避免緩存
var url = "/ajax_yhyz/registerProcess.php?mytime=" + new Date().getTime()
+ "&username=" + getValue('username').value;
myXmlHttpRequest.open("get", url, true); // true 表示異步
myXmlHttpRequest.onreadystatechange = chuli;
myXmlHttpRequest.send(null); // GET 請求填 null
}
}
function chuli(){
if(myXmlHttpRequest.readyState == 4){
getValue("myres").value = myXmlHttpRequest.responseText;
}
}
function getValue(id){
return document.getElementById(id); // 返回元素本身,才能局部刷新
}
</script>
<form>
用戶名:<input type="text" id="username">
<input type="button" onclick="checkName()" value="驗證用戶名">
<input type="text" id="myres" />
</form>
<?php
$username = $_REQUEST['username'];
if($username == "shunping"){
echo "err";
}else{
echo "ok";
}
?>
點擊驗證後,Ajax 異步請求後端判斷用戶名,再把結果寫入 #myres 輸入框,全程無刷新,實現局部更新。注意:GET 提交若 URL 不變會命中緩存,加時間戳或設置 no-cache meta 可規避。