网页编程 - AJAX ASP请求实例

<html>

<head>

<script type="text/javascript">

function showHint(str)

{

var xmlhttp;

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","/ajax/gethint.asp?q="+str,true);

xmlhttp.send();

}

</script>

</head>

<body>

<h3>请在下面的输入框中键入字母(A - Z):</h3>

<form action=""> 

姓氏:<input type="text" id="txt1" onkeyup="showHint(this.value)" />

</form>

<p>建议:<span id="txtHint"></span></p> 

</body>

</html>

ASP 文件

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

<%

response.expires=-1

dim a(30)

'用名字来填充数组

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"

'获得来自 URL 的 q 参数

q=ucase(request.querystring("q"))

'如果 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

'如果未找到提示,则输出 "no suggestion"

'否则输出正确的值

if hint="" then

  response.write("no suggestion")

else

  response.write(hint)

end if

%>