ASP – AJAX 与 ASP

asp - ajax 与 asp

ajax 被用于创建交互性更强的应用程序。

ajax asp 实例

下面的实例将演示当用户在输入框中键入字符时,网页如何与 web 服务器进行通信:

实例

start typing a name in the input field below:

function showhint(str) { if (str.length==0) { 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","gethint.asp?q="+str,true); xmlhttp.send(); } first name:

suggestions:


实例解释 - html 页面

当用户在上面的输入框中键入字符时,会执行 "showhint()" 函数。该函数由 "onkeyup" 事件触发:





function showhint(str)
{
if (str.length==0)
{
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","gethint.asp?q="+str,true);
xmlhttp.send();
}



start typing a name in the input field below:



first name:

suggestions:




源代码解释:

如果输入框是空的(str.length==0),该函数会清空 txthint 占位符的内容,并退出该函数。

如果输入框不是空的,那么 showhint() 会执行以下步骤:

  • 创建 xmlhttprequest 对象
  • 创建在服务器响应就绪时执行的函数
  • 向服务器上的文件发送请求
  • 请注意添加到 url 末端的参数(q)(包含输入框的内容)

asp 文件

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

"gethint.asp" 中的源代码会检查姓名数组,然后向浏览器返回对应的姓名:

<%
response.expires=-1
dim a(30)
'fill up array with names
a(1)="anna"
a(2)="brittany"
a(3)="cinderella"
a(4)="diana"
a(5)="eva"
a(6)="fiona"
a(7)="gunda"
a(8)="hege"
a(9)="inga"
a(10)="johanna"
a(11)="kitty"
a(12)="linda"
a(13)="nina"
a(14)="ophelia"
a(15)="petunia"
a(16)="amanda"
a(17)="raquel"
a(18)="cindy"
a(19)="doris"
a(20)="eve"
a(21)="evita"
a(22)="sunniva"
a(23)="tove"
a(24)="unni"
a(25)="violet"
a(26)="liza"
a(27)="elizabeth"
a(28)="ellen"
a(29)="wenche"
a(30)="vicky"

'get the q parameter from url
q=ucase(request.querystring("q"))

'lookup all hints from array if length of q>0
if len(q)>0 then
hint=""
for i=1 to 30
if q=ucase(mid(a(i),1,len(q))) then
if hint="" then
hint=a(i)
else
hint=hint & " , " & a(i)
end if
end if
next
end if

'output "no suggestion" if no hint were found
'or output the correct values
if hint="" then
response.write("no suggestion")
else
response.write(hint)
end if
%>

解释:如果 javascript 发送了任何文本(即 strlen($q) > 0),则会发生:

  • 查找匹配 javascript 发送的字符的姓名
  • 如果未找到匹配,则将响应字符串设置为 "no suggestion"
  • 如果找到一个或多个匹配姓名,则用所有姓名设置响应字符串
  • 把响应发送到 "txthint" 占位符

  • 相关文章