学ajax前要学数据库,AJAX 数据库实例

AJAX 数据库实例

AJAX 可用来与数据库进行交互式通信。

AJAX 数据库实例

下面的实例将演示网页如何通过 AJAX 从数据库读取信息:

实例

Select a customer: Alfreds Futterkiste North/South Wolski Zajazd

Customer info will be listed here...

实例解释 - HTML 页面

当用户在上面的下拉列表中选择某位客户时,会执行名为 "showCustomer()" 的函数。该函数由 "onchange" 事件触发:

function showCustomer(str)

{

if (str=="")

{

document.getElementById("txtHint").innerHTML="";

return;

}

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for 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();

}

Select a customer:

Alfreds Futterkiste

North/South

Wolski Zajazd

Customer info will be listed here...

源代码解释:

如果没有选择客户(str.length==0),那么该函数会清空 txtHint 占位符,然后退出该函数。

如果已选择一位客户,则 showCustomer() 函数会执行以下步骤:

创建 XMLHttpRequest 对象

创建在服务器响应就绪时执行的函数

向服务器上的文件发送请求

请注意添加到 URL 末端的参数(q)(包含下拉列表的内容)

ASP 文件

上面这段通过 JavaScript 调用的服务器页面是名为 "getcustomer.asp" 的 ASP 文件。

"getcustomer.asp" 中的源代码会运行一次针对数据库的查询,然后在 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("

do until rs.EOF

for each x in rs.Fields

response.write("

" & x.name & "")

response.write("

" & x.value & "")

next

rs.MoveNext

loop

response.write("

")

%>

你可能感兴趣的:(学ajax前要学数据库)