AJAX PHP 实例
内容摘要
AJAX PHP 实例
文章正文
AJAX 用于创建更具交互性的应用程序。
AJAX PHP 实例
下面的例子演示:当用户在输入字段中键入字符时,网页如何与 web 服务器进行通信:
实例
请在下面的输入字段中键入字母 A-Z:
姓名:
搜索建议:
例子解释
在上面的例子中,当用户在输入字段中键入字符时,会执行名为 "showHint()" 的函数。
此函数被 onkeyup 事件触发。
下面是 HTML 代码:
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <html> <head> <script> function showHint(str) { if (str.length == 0) { document.getElementById( "txtHint" ).innerHTML = "" ; return ; } else { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { if ( this .readyState == 4 && this .status == 200) { document.getElementById( "txtHint" ).innerHTML = this .responseText; } }; xmlhttp.open( "GET" , "gethint.php?q=" + str, true ); xmlhttp.send(); } } </script> </head> <body> <p><b>请在下面的输入字段中键入姓名:</b></p> <form> 姓或名:<input type= "text" onkeyup= "showHint(this.value)" > </form> <p>建议:<span id= "txtHint" ></span></p> </body> </html> |
代码解释:
首先,检查输入字段是否为空(str.length == 0),如果是,清空 txtHint 占位符的内容并退出函数。
不过,如果输入字段不为空,则进行如下:
- 创建 XMLHttpRequest 对象
- 创建当服务器响应就绪时执行的函数
- 发送请求到服务器上的 PHP 文件(gethint.php)
- 请注意添加到 gethint.php 的 q 参数
- str 变量保存了输入字段的内容
PHP 文件 - "gethint.php"
这个 PHP 文件检查姓名数组,然后向浏览器返回对应的姓名:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | <?php // 姓名数组 $a[] = "Ava" ; $a[] = "Brielle" ; $a[] = "Caroline" ; $a[] = "Diana" ; $a[] = "Elise" ; $a[] = "Fiona" ; $a[] = "Grace" ; $a[] = "Hannah" ; $a[] = "Ileana" ; $a[] = "Jane" ; $a[] = "Kathryn" ; $a[] = "Laura" ; $a[] = "Millie" ; $a[] = "Nancy" ; $a[] = "Opal" ; $a[] = "Petty" ; $a[] = "Queenie" ; $a[] = "Rose" ; $a[] = "Shirley" ; $a[] = "Tiffany" ; $a[] = "Ursula" ; $a[] = "Victoria" ; $a[] = "Wendy" ; $a[] = "Xenia" ; $a[] = "Yvette" ; $a[] = "Zoe" ; $a[] = "Angell" ; $a[] = "Adele" ; $a[] = "Beatty" ; $a[] = "Carlton" ; $a[] = "Elisabeth" ; $a[] = "Violet" ; // 从 URL 获取 q 参数 $q = $_REQUEST[ "q" ]; $hint = "" ; // 查看数组中所有 hint,$q 是否与 "" 相同 if ($q !== "" ) { $q = strtolower($q); $len=strlen($q); foreach($a as $name) { if (stristr($q, substr($name, 0, $len))) { if ($hint === "" ) { $hint = $name; } else { $hint .= ", $name" ; } } } } // 输出 "no suggestion",如果未找到 hint 或输出正确的值 echo $hint === "" ? "no suggestion" : $hint; ?> |
代码注释