ajax 可用來與數據庫進行動態地通信。
在下面的 ajax 例子中,我們將演示如何使用 ajax 技術令網頁從數據庫讀取信息。
上面的實例包含了一個簡單的 html 表單以及執行 javascript 的鏈接:
<html><head><script src="selectcustomer.js"></script>
</head><body><form>
請選擇一位客戶:<selectname="customers" onchange="showcustomer(this.value)"
><option value="alfki">alfreds futterkiste<option value="norts ">north/south<option value="wolza">wolski zajazd </select></form>
<p><divid="txthint"
><b>客戶信息將在此處列出。</b></div></p></body></html>
正如您看到的,這是一個簡單的帶有一個名為 "customers" 下拉列表的 html 表單。
表單以下的段落包含了一個名為 "txthint" 的 div,這個 div 充當了由 web 服務器所取回的信息的位置占位符。
當用戶選擇數據時,名為 "showcustomer()" 的函數會被執行。函數的執行會被 "onchange" 事件觸發。另外需要說明的是:每當用戶改變下拉列表中的值,函數 showcustomer 就會被調用。
下面列出了 javascript 代碼。
這是存儲在文件 "selectcustomer.js" 中的 javascript 代碼:
var xmlhttpfunction showcustomer(str)
{ xmlhttp=getxmlhttpobject();if (xmlhttp==null) { alert ("您的瀏覽器不支持ajax!"); return; } var url="getcustomer.asp";url=url+"?q="+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 xmlhttp=null;try { // firefox, opera 8.0+, safari xmlhttp=new xmlhttprequest(); }catch (e) { // internet explorer try { xmlhttp=new activexobject("msxml2.xmlhttp"); } catch (e) { xmlhttp=new activexobject("microsoft.xmlhttp"); } }return xmlhttp;}
這個被 javascript 調用的服務器頁面,是一個名為 "getcustomer.asp" 的簡單的 asp 文件。
此頁面使用 vbscript 針對 iis 編寫。可以使用 php 或其他服務器語言對它進行改寫。
此代碼可運行針對某個數據庫的 sql,并以 html 表格返回結果:
<%response.expires=-1sql="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, connresponse.write("<table>")do until rs.eof for each x in rs.fields response.write("<tr><td><em>" & x.name & "</em></td>") response.write("<td>" & x.value & "</td></tr>") next rs.movenextloopresponse.write("</table>")%>
新聞熱點
疑難解答
圖片精選