Ajax 是建立在 XMLHTTP 元件之上的技術。這份範例把 POST 流程拆成「前端頁面」與「後端接收」兩個檔案,並在關鍵行加上詳細註解,適合第一次動手的人。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>相容多瀏覽器的 AJAX 入門實例</title>
<script type="text/javascript">
var xmlHttp;
// 建立 XMLHTTP 物件:IE 走 ActiveX,非 IE 走原生建構式
function createXMLHttp() {
if (window.XMLHttpRequest) { // Mozilla 系
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { }
}
}
}
// 主流程
function startXMLHttp() {
createXMLHttp();
var send_string = "name=" + document.getElementById("name").value;
send_string = encodeURI(send_string);
xmlHttp.onreadystatechange = dodo; // 控制傳輸過程
xmlHttp.open("post", "ajax_show.php", true); // 方法/網址/是否非同步
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(send_string);
}
function dodo() {
if (xmlHttp.readyState == 4) { // 4 表示傳輸完畢
if (xmlHttp.status == 200) { // 200 = OK,404 = Not Found
document.getElementById("content").innerHTML = xmlHttp.responseText;
}
}
}
</script>
</head>
<body>
<span id="content">要被替換的內容</span><br>
<input type="button" onclick="javascript:startXMLHttp()" value="AJAX 取得" />
<form id="form1" name="form1" method="post" action="">
<input type="text" name="name" id="name" />
</form>
</body>
</html>
<?php $content = isset($_POST['name']) ? $_POST['name'] : ''; echo $content; ?>
$_POST 會是空的。encodeURI,含中文時建議改用 encodeURIComponent,並在後端用 header('Content-Type: text/html; charset=utf-8') 對齊編碼。理解這份骨架之後,換成任何後端語言都不需要改動前端結構——這正是 Ajax 當年最大的價值:把資料交換從「整頁刷新」裡解放出來。