從網頁前端輸入提示范圍內的字符,然後顯示從後台返回的結果
1: <html>
2: <head>
3: <meta http-equiv="content-type" content="text/html;charset=utf-8">
4: <script type="text/javascript">
5: function showHint(str)
6: {
7: var xmlhttp;
8: if (str.length==0)
9: {
10: document.getElementById("txtHint").innerHTML="";
11: return;
12: }
13: if (window.XMLHttpRequest)
14: {// code for IE7+, Firefox, Chrome, Opera, Safari
15: xmlhttp=new XMLHttpRequest();
16: }
17: else
18: {// code for IE6, IE5
19: xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
20: }
21: xmlhttp.onreadystatechange=function()
22: {
23: if (xmlhttp.readyState==4 && xmlhttp.status==200)
24: {
25: document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
26: }
27: }
28: xmlhttp.open("GET","ajax.php?q="+str,true);
29: xmlhttp.send();
30: }
31: </script>
32: </head>
33: <body>
34:
35: <h3>請在下面的輸入框中鍵入字母(A - Z):</h3>
36: <form action="">
37: 姓氏:<input type="text" id="txt1" onkeyup="showHint(this.value)" />
38: </form>
39: <p>建議:<span id="txtHint"></span></p>
40:
41: </body>
42: </html>
如果輸入框為空 (str.length==0),則該函數清空 txtHint 占位符的內容,並退出函數。
如果輸入框不為空,showHint() 函數執行以下任務:
php:
1: <?php
2: // 用名字來填充數組
3: $a[]="Anna";
4: $a[]="Brittany";
5: $a[]="Cinderella";
6: $a[]="Diana";
7: $a[]="Eva";
8: $a[]="Fiona";
9: $a[]="Gunda";
10: $a[]="Hege";
11: $a[]="Inga";
12: $a[]="Johanna";
13: $a[]="Kitty";
14: $a[]="Linda";
15: $a[]="Nina";
16: $a[]="Ophelia";
17: $a[]="Petunia";
18: $a[]="Amanda";
19: $a[]="Raquel";
20: $a[]="Cindy";
21: $a[]="Doris";
22: $a[]="Eve";
23: $a[]="Evita";
24: $a[]="Sunniva";
25: $a[]="Tove";
26: $a[]="Unni";
27: $a[]="Violet";
28: $a[]="Liza";
29: $a[]="Elizabeth";
30: $a[]="Ellen";
31: $a[]="Wenche";
32: $a[]="Vicky";
33:
34: //獲得來自 URL 的 q 參數
35: $q=$_GET["q"];
36:
37: //如果 q 大於 0,則查找數組中的所有提示
38: if (strlen($q) > 0)
39: {
40: $hint="";
41: for($i=0; $i<count($a); $i++)
42: {
43: if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
44: {
45: if ($hint=="")
46: {
47: $hint=$a[$i];
48: }
49: else
50: {
51: $hint=$hint." , ".$a[$i];
52: }
53: }
54: }
55: }
56:
57: // 如果未找到提示,則把輸出設置為 "no suggestion"
58: // 否則設置為正確的值
59: if ($hint == "")
60: {
61: $response="no suggestion";
62: }
63: else
64: {
65: $response=$hint;
66: }
67:
68: //輸出響應
69: echo $response;
70: ?>
效果