当输入j后,会触发ajax效果,从后台获取相应的名字中带有j的数据,并展示在suggestions中。
代码实现如下:
实现ajax需要三个文件,一个是html的表单文件,一个是js的核心文件,一个是php的后台文件。
下面的是html文件,当键盘按下时触发showHint方法,在showHint方法中会有ajax的核心内容,实例化,获取地址,获取数据并展示等等。
<BR><BR><script src="clienthint.js"></script> <BR></P><P><body></P><P> <BR>First Name:<BR><input type="text" id="txt1"<BR>onkeyup="showHint(this.value)"><BR></P><P><p>Suggestions: <span id="txtHint"></span></p></P><P><BR><BR>
下面是js的内容clienthint.js。
var xmlHttp</P><P>function showHint(str)<BR>{<BR>if (str.length==0)<BR> { <BR> document.getElementById("txtHint").innerHTML=""<BR> return<BR> }<BR>//获取xmlHttpObject对象,如果为空,提示浏览器不支持ajax<BR>xmlHttp=GetXmlHttpObject()<BR>if (xmlHttp==null)<BR> {<BR> alert ("Browser does not support HTTP Request")<BR> return<BR> } <BR> //获取url<BR>var url="gethint.php"<BR>url=url+"?q="+str<BR>url=url+"&sid="+Math.random()<BR> //回调函数,执行动作<BR>xmlHttp.onreadystatechange=stateChanged <BR> //open<BR>xmlHttp.open("GET",url,true)<BR>xmlHttp.send(null)<BR>} </P><P>function stateChanged() <BR>{ <BR>if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")<BR>{ <BR>//将获取的信息插入到txtHint中<BR>document.getElementById("txtHint").innerHTML=xmlHttp.responseText <BR>} <BR>}</P><P><BR>//获取xml对象<BR>function GetXmlHttpObject()<BR>{<BR>var xmlHttp=null;<BR>try<BR>{<BR>// Firefox, Opera 8.0+, Safari<BR>xmlHttp=new XMLHttpRequest();<BR>}<BR>catch (e)<BR>{<BR>// Internet Explorer<BR>try<BR> {<BR> xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");<BR> }<BR>catch (e)<BR> {<BR> xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");<BR> }<BR>}<BR>return xmlHttp;<BR>}<BR>
下面是php的内容。根据ajax对象传入的参数,获取相应的数据。
<?php<BR>// Fill up array with names<BR>$a[]="Anna";<BR>$a[]=<strong style="color:transparent">¥本文来源gaodai#ma#com搞@@代~&码网^</strong><small>搞gaodaima代码</small>"Brittany";<BR>$a[]="Cinderella";<BR>$a[]="Diana";<BR>$a[]="Eva";<BR>$a[]="Fiona";<BR>$a[]="Gunda";<BR>$a[]="Hege";<BR>$a[]="Inga";<BR>$a[]="Johanna";<BR>$a[]="Jiqing";<BR>$a[]="Kitty";<BR>$a[]="Linda";<BR>$a[]="Nina";<BR>$a[]="Ophelia";<BR>$a[]="Petunia";<BR>$a[]="Amanda";<BR>$a[]="Raquel";<BR>$a[]="Cindy";<BR>$a[]="Doris";<BR>$a[]="Eve";<BR>$a[]="Evita";<BR>$a[]="Sunniva";<BR>$a[]="Tove";<BR>$a[]="Unni";<BR>$a[]="Violet";<BR>$a[]="Liza";<BR>$a[]="Elizabeth";<BR>$a[]="Ellen";<BR>$a[]="Wenche";<BR>$a[]="Vicky";</P><P>//get the q parameter from URL<BR>$q=$_GET["q"];</P><P>//lookup all hints from array if length of q>0<BR>if (strlen($q) > 0)<BR>{<BR>$hint="";<BR>for($i=0; $i<count($a); $i++)<BR> {<BR> if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))<BR> {<BR> if ($hint=="")<BR> {<BR> $hint=$a[$i];<BR> }<BR> else<BR> {<BR> $hint=$hint." , ".$a[$i];<BR> }<BR> }<BR> }<BR>}</P><P>//Set output to "no suggestion" if no hint were found<BR>//or to the correct values<BR>if ($hint == "")<BR>{<BR>$response="no suggestion";<BR>}<BR>else<BR>{<BR>$response=$hint;<BR>}</P><P>//output the response<BR>echo $response;<BR>?><BR>