AJAX 数据库

ajax 数据库实例

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

ajax 数据库实例

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

实例

function showcustomer(str) { var xmlhttp; 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...

实例解释 - 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("")
response.write("")
next
rs.movenext
loop
response.write("
" & x.name & " " & x.value & "
")
%>

相关文章