AJAX数据库实例
AJAX可利用与数据库进行动态通信。
实例解释-showCustomer()函数
当用户在上面的下拉列表中选择某个客户时,会执行名为“ showCustomer()”的函数。该函数由“ onchange”事件触发:
函数showCustomer (str ){ var xmlhttp ; if (str == “ ” ){文档。getElementById (“ txtHint ” )。innerHTML = “ ” ; 回报; }如果(窗口。XMLHttpRequest的){ // IE7 +,火狐,铬,歌剧,Safari浏览器执行代码 xmlhttp = new XMLHttpRequest (); } else { // IE6,IE5浏览器执行代码 xmlhttp = new ActiveXObject (“ Microsoft.XMLHTTP ” ); } xmlhttp 。的onreadystatechange =函数(){如果(XMLHTTP 。readyState的== 4 && XMLHTTP 。状态== 200 ){文档。getElementById (“ txtHint ” )。innerHTML = xmlhttp 。responseText ; } } xmlhttp 。打开(“ GET ” ,“ /try/ajax/getcustomer.php?q= ” + str ,true ); xmlhttp 。发送(); }
showCustomer()函数执行以下任务:
- 检查是否已选择某个客户
- 创建XMLHttpRequest对象
- 当服务器响应及时时执行所创建的函数
- 把请求发送到服务器上的文件
- 请注意我们向URL添加了一个参数q(带有输入域中的内容)
AJAX服务器页面
由上面的JavaScript调用的服务器页面是PHP文件,称为“ getcustomer.php”。
请用PHP编写服务器文件也很容易,或者使用其他服务器语言。
“ getcustomer.php”中的源代码负责对数据库进行查询,然后用HTML表格返回结果:
<%
response.expires = -1
sql =“ SELECT *从客户所在客户==”
sql = sql&“'”&request.querystring(“ q”)&“'”
设置conn = Server.CreateObject(“ ADODB.Connection”)
conn.Provider =“ Microsoft.Jet.OLEDB.4.0”
conn.Open(Server.Mappath(“ / db / northwind.mdb”))
设置rs = Server.CreateObject(“ ADODB.recordset”)
rs.Open sql,conn
response.write(“ <table>”)
直到EOF为止
对于rs.Fields中的每个x
response.write(“ <tr> <td> <b>”&x.name&“ </ b> </ td>”)
response.write(“ <td>”&x.value&“ </ td> </ tr>”)
下一个
rs.MoveNext
循环
response.write(“ </ table>”)
%>