AJAX 數(shù)據(jù)庫實例
AJAX 可用來與數(shù)據(jù)庫進行相互的通信。
實例解釋 - HTML 頁面
當用戶在上面的下拉列表中選擇某位客戶時,會執(zhí)行名為 "showCustomer()" 的函數(shù)。該函數(shù)由 "onchange" 事件觸發(fā):
<!DOCTYPE html> <html> <head> <script> function showCustomer(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// 針對 IE7+, Firefox, Chrome, Opera, Safari 的代碼 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="">Select a customer:</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>
源代碼解釋:
如果沒有選擇客戶(str.length 等于 0),那么該函數(shù)會清空 txtHint 占位符,然后退出該函數(shù)。
如果已選擇一位客戶,則 showCustomer() 函數(shù)會執(zhí)行以下步驟:
- 創(chuàng)建 XMLHttpRequest 對象
- 創(chuàng)建在服務器響應就緒時執(zhí)行的函數(shù)
- 向服務器上的文件發(fā)送請求
- 請注意添加到 URL 末端的參數(shù)(q)(包含下拉列表的內容)
ASP 文件
上面這段 JavaScript 調用的服務器頁面是名為 "getcustomer.asp" 的 ASP 文件。
"getcustomer.asp" 中的源代碼會運行一次針對數(shù)據(jù)庫的查詢,然后在 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>") %>