使用者在輸入框打字,下方即時列出符合的名字——這是 Ajax 最常被引用的入門範例。它由三個部分組成:一個 HTML 表單、一支 JavaScript、一個 PHP 頁面。
<html>
<head>
<script src="clienthint.js"></script>
</head>
<body>
<form>
First Name:
<input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>
<p>建議:<span id="txtHint"></span></p>
</body>
</html>
結構很單純:一個 id 為 txt1 的輸入框,鍵盤放開時觸發 showHint;下方 id 為 txtHint 的 span 作為回應內容的落點。
var xmlHttp;
function showHint(str) {
if (str.length === 0) {
document.getElementById('txtHint').innerHTML = '';
return;
}
xmlHttp = GetXmlHttpObject();
if (xmlHttp === null) {
alert('此瀏覽器不支援 HTTP Request');
return;
}
var url = 'gethint.php';
url = url + '?q=' + encodeURIComponent(str);
url = url + '&sid=' + Math.random(); // 破快取
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open('GET', url, true);
xmlHttp.send(null);
}
function stateChanged() {
if (xmlHttp.readyState === 4) {
document.getElementById('txtHint').innerHTML = xmlHttp.responseText;
}
}
function GetXmlHttpObject() {
var http = null;
try {
http = new XMLHttpRequest(); // Firefox、Opera 8+、Safari
} catch (e) {
try {
http = new ActiveXObject('Msxml2.XMLHTTP'); // IE
} catch (e) {
try {
http = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) { }
}
}
return http;
}
showHint 的六個步驟值得記住:定義要送去的 URL、把輸入值作為參數 q 附加、加上隨機數避免用到快取、建立 XMLHTTP 物件並指定狀態改變時要呼叫的函數、以指定 URL 開啟物件、送出請求。輸入框為空時則直接清空提示區。
<?php
$a = array('Anna', 'Brittany', 'Cinderella', 'Diana', 'Eva', 'Fiona',
'Gunda', 'Hege', 'Inga', 'Johanna', 'Kitty', 'Linda', 'Nina');
$q = $_GET['q'];
if (strlen($q) > 0) {
$hint = '';
for ($i = 0; $i < count($a); $i++) {
if (strtolower($q) === strtolower(substr($a[$i], 0, strlen($q)))) {
if ($hint === '') {
$hint = $a[$i];
} else {
$hint = $hint . ' , ' . $a[$i];
}
}
}
}
echo ($hint === '') ? 'no suggestion' : $hint;
?>
邏輯是逐項比對每個名字的開頭字母是否與輸入相符(用 strtolower 讓比對不分大小寫),把符合的串成一串;若一個都沒有就回 no suggestion。
這個範例是教學用的骨架,正式環境需要補上:
另外,輸出到 innerHTML 的內容若可能含使用者資料,務必先做 HTML 編碼。這個小細節,是無數 XSS 漏洞的起點。