大致是两个步骤:客户端触发读取数据请求,服务器端接收请求查询数据库并返回结果。
1、客户端请求
假设从页面的下拉列表中选择一个客户,当用户在下拉列表中选择某个客户时,会执行名为 "showCustomer()" 的函数。该函数由 "onchange" 事件触发:
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()
}
2、服务器端响应,asp示例:
<%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>")
%>
<html><head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp
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("myDiv").innerHTML=xmlhttp.responseText
}
}
xmlhttp.open("POST","ASP文件.asp",true)
xmlhttp.send()
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv">这是一个div</div>
</body>
</html>
看看w3school的讲解吧,我就是这里学来的,里面有例子
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)