AJAX 技術能讓網頁與資料庫進行非同步互動,無需重新整理頁面即可動態更新資料。
下方範例展示如何透過下拉選單選擇客戶,即時從資料庫撈取並顯示該客戶詳細資訊。
當使用者在下拉選單選擇客戶時,會觸發 onchange 事件,呼叫 showCustomer() 函式:
<!DOCTYPE html>
<html>
<head>
<script>
function showCustomer(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
var xmlhttp;
if (window.XMLHttpRequest) {
// 現代瀏覽器
xmlhttp = new XMLHttpRequest();
} else {
// IE6、IE5 相容
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "getcustomer.asp?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="customers" onchange="showCustomer(this.value)">
<option value="">請選擇客戶:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<br>
<div id="txtHint">客戶資訊將顯示於此…</div>
</body>
</html>
邏輯說明:
XMLHttpRequest 物件(含舊版 IE 相容處理)。txtHint 區塊。getcustomer.asp,並將選取的客戶代碼作為查詢參數 q 傳遞。伺服器端的 getcustomer.asp 接收查詢參數,對 Northwind 資料庫執行 SQL 查詢,並以 HTML 表格形式回傳結果:
<%
response.expires = -1
sql = "SELECT * FROM CUSTOMERS WHERE CUSTOMERID = "
sql = sql & "'" & request.querystring("q") & "'"
set conn = Server.CreateObject("ADODB.Connection")
conn.Provider = "Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs = Server.CreateObject("ADODB.recordset")
rs.Open sql, conn
response.write("<table>")
do until rs.EOF
for each x in rs.Fields
response.write("<tr><td><b>" & x.name & "</b></td>")
response.write("<td>" & x.value & "</td></tr>")
next
rs.MoveNext
loop
response.write("</table>")
%>
注意:此範例使用傳統 ASP 與 Access 資料庫,實務上建議採用參數化查詢以防 SQL 注入,並考慮改用 ASP.NET、PHP 或 Node.js 等現代架構。