這是一個以純 JavaScript 實作的搜尋自動完成範例。使用者在 CompanyName 欄位輸入文字時,程式會查詢 SQL Server 2000 的 Northwind 資料庫中 Suppliers 表的 CompanyName 欄位,並把符合的結果以清單形式即時呈現。
整個範例由四個檔案組成:一個 HTML 頁面、一個 ASPX 頁面、其後端程式碼,以及一份負責把 XML 轉成表格的 XSLT 檔。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>輸入自動完成</title>
<script language="javascript">
var txtInput; // 輸入框
var currentIndex = -1; // 目前選中項的索引
// 初始化參數並定位下拉清單
function initPar() {
txtInput = document.getElementById("txtCompanyName");
setPosition();
}
// 讓下拉清單對齊輸入框
function setPosition() {
var width = txtInput.offsetWidth;
var left = getLength("offsetLeft");
var top = getLength("offsetTop") + txtInput.offsetHeight;
divContent.style.left = left + "px";
divContent.style.top = top + "px";
divContent.style.width = width + "px";
}
// 累加取得絕對座標
function getLength(attr) {
var offset = 0;
var item = txtInput;
while (item) {
offset += item[attr];
item = item.offsetParent;
}
return offset;
}
// 自動完成主流程
function autoComplete() {
// 上下鍵或 Enter:改為在清單中選擇
if (event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 13) {
selItemByKey();
} else {
if (txtInput.value == "") {
divContent.style.display = 'none';
return;
}
currentIndex = -1;
// 附帶時間戳避免快取
requestObj = new ActiveXObject("Microsoft.XMLHTTP");
requestObj.onreadystatechange = displayResult;
requestObj.open("POST",
"AutoComplete.aspx?ts=" + new Date().toLocaleString(), true);
requestObj.send(txtInput.value);
}
}
function displayResult() {
if (requestObj.readyState == 4) {
showData();
divContent.style.display = "";
}
}
// 以 XSLT 把 XML 轉成下拉表格
function showData() {
var doc = new ActiveXObject("MSXML2.DOMDocument.3.0");
doc.loadXML(requestObj.responseText);
var docStyle = new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
docStyle.async = false;
docStyle.load("list.xslt");
var docTemplate = new ActiveXObject("MSXML2.XSLTemplate");
docTemplate.stylesheet = docStyle;
var processor = docTemplate.createProcessor();
processor.input = doc;
processor.transform();
divContent.innerHTML = processor.output;
}
// 以鍵盤在清單中移動
function selItemByKey() {
var tbl = document.getElementById("tblContent");
if (!tbl) { return; }
var maxRow = tbl.rows.length;
if (event.keyCode == 38 && currentIndex > 0) {
currentIndex--; // 向上
} else if (event.keyCode == 40 && currentIndex < maxRow - 1) {
currentIndex++; // 向下
} else if (event.keyCode == 13) {
selValue(); return; // Enter
}
clearColor();
txtInput.value = tbl.rows[currentIndex].innerText;
tbl.rows[currentIndex].style.backgroundColor = "InfoBackground";
}
function clearColor() {
var tbl = document.getElementById("tblContent");
for (var i = 0; i < tbl.rows.length; i++) {
tbl.rows[i].style.backgroundColor = "";
}
}
function selValue() {
if (event.keyCode != 13) {
txtInput.value = event.srcElement.innerText; // 滑鼠點選
}
initList();
}
// 失去焦點時收起清單
function setDisplay() {
if (document.activeElement.tagName == "TD") {
var tbl = document.activeElement.parentElement
.parentElement.parentElement;
if (tbl.id != "tblContent") { initList(); }
return;
}
initList();
}
function initList() {
divContent.style.display = 'none';
divContent.innerHTML = "";
currentIndex = -1;
}
</script>
</head>
<body>
CompanyName
<input type="text" id="txtCompanyName" onkeyup="autoComplete()"
onblur="setDisplay();" style="width:400px" />
<!-- 顯示下拉清單的容器 -->
<div id="divContent" style="display:none; position:absolute;"</div>
</body>
</html>
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Configuration;
namespace AjaxBaseHome
{
public partial class AutoComplete : System.Web.UI.Page
{
private static string conString =
WebConfigurationManager.ConnectionStrings["myData"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
string input = GetInput();
Response.Write(GetCompanyName(input));
}
// 讀取 POST 送來的字串
private string GetInput()
{
Stream s = Request.InputStream;
int count = 0;
byte[] buffer = new byte[1024];
StringBuilder builder = new StringBuilder();
while ((count = s.Read(buffer, 0, 1024)) > 0)
{
builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
}
return builder.ToString();
}
// 以參數化查詢避免 SQL injection
private string GetCompanyName(string input)
{
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand command = new SqlCommand(
"select * from Suppliers where CompanyName like @Name", con);
command.Parameters.Add(new SqlParameter("@name", input + "%"));
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds.GetXml();
}
}
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="https://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" />
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="NewDataSet">
<table id="tblContent" style="background-color:GrayText">
<xsl:for-each select="Table">
<tr>
<td style="cursor:hand"
onclick="selValue()"
onmouseover="this.style.backgroundColor='InfoBackground'"
onmouseout="this.style.backgroundColor=''">
<xsl:value-of select="CompanyName" />
</td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
因為下拉清單必須浮在輸入框正下方,而輸入框可能位於頁面的任意深度,所以要沿著 offsetParent 鏈一路累加,才能得到相對於文件的絕對位置。
網址後面加上 ?ts= 時間戳,是為了避免 POST 結果被瀏覽器快取,導致第二次輸入時拿到舊資料。
currentIndex 負責記錄鍵盤游標位置,selValue() 則同時處理 Enter 與滑鼠點擊兩種收操作方法,並在選完後呼叫 initList() 清空狀態。
後端已改用參數化查詢(@Name)而非字串拼接,這是必須堅持的做法——自動完成欄位每敲一個字就會打一次資料庫,若用字串拼接,等於把 SQL injection 的風險放大了數十倍。
這份範例使用 ActiveX 的 Microsoft.XMLHTTP 與 MSXML2 系列物件,只在 Internet Explorer 下有效。若要在現代專案實作相同功能,請改用 fetch 或 XMLHttpRequest 搭配 JSON.parse(),前端可直接使用 <datalist> 或 jQuery UI Autocomplete,並記得加上 debounce(輸入停止約 300ms 後才發送請求),以免對伺服器造成不必要的負擔。