利用 AJAX 技術,在使用者輸入文字時即時向伺服器請求建議資料,打造流暢的自動完成體驗。
在下方輸入框輸入名字,系統會即時顯示符合的建議名單:
請在下方輸入框開始輸入名字:
建議名單:
當使用者在輸入框按鍵放開(onkeyup)時,觸發 showHint() 函式:
<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "gethint.asp?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<p><b>請在下方輸入框開始輸入名字:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)" size="20">
</form>
<p>建議名單: <span id="txtHint"></span></p>
</body>
</html>
運作流程:
gethint.asp,查詢參數 q 為使用者輸入的文字。gethint.asp 內建一個姓名陣列,接收查詢參數後進行前綴比對,回傳符合的名單:
<%
response.expires = -1
dim a(30)
' 填入測試用姓名資料
a(1) = "Anna"
a(2) = "Brittany"
a(3) = "Cinderella"
' ... 略,共 30 筆 ...
a(30) = "Vicky"
' 取得查詢參數並轉大寫
q = ucase(request.querystring("q"))
' 比對邏輯
if len(q) > 0 then
hint = ""
for i = 1 to 30
if q = ucase(mid(a(i), 1, len(q))) then
if hint = "" then
hint = a(i)
else
hint = hint & " , " & a(i)
end if
end if
next
end if
' 輸出結果
if hint = "" then
response.write("no suggestion")
else
response.write(hint)
end if
%>
補充說明:實務應用中,建議改用資料庫查詢並搭配 LIMIT 限制筆數,且前端可改用 fetch API 或現代框架(如 Vue、React)實作更優雅的自動完成元件。