AJAX 数据库
-
定义和使用
AJAX用于创建更多交互式应用程序。以下示例演示了当用户在输入字段中键入字符时,网页如何与Web服务器通信:
尝试一下<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>Start typing a name in the input field below:</b></p> <form> First name: <input type="text" onkeyup="showHint(this.value)"> </form> <p>Suggestions: <span id="txtHint"></span></p> </body> </html>
-
示例说明
在上面的示例中,当用户在输入字段中键入字符时,showHint()执行被调用的函数。该函数由onkeyup事件触发。代码说明:首先,检查input字段是否为空(str.length == 0)。如果是,请清除txtHint占位符的内容并退出该函数。但是,如果输入字段不为空,请执行以下操作:- 创建XMLHttpRequest对象
- 创建服务器响应准备好时要执行的函数
- 将请求发送到服务器上的PHP文件(gethint.php)
- 请注意,“gethint.php?q=“+ str添加了q参数
- str变量保存input字段的内容
-
PHP文件 - “gethint.php”
PHP文件检查名称数组,并将相应的名称返回给浏览器:<?php // 带名字的数组 $a[] = "Anna"; $a[] = "Brittany"; $a[] = "Cinderella"; $a[] = "Diana"; $a[] = "Eva"; $a[] = "Fiona"; $a[] = "Gunda"; $a[] = "Hege"; $a[] = "Inga"; $a[] = "Johanna"; $a[] = "Kitty"; $a[] = "Linda"; $a[] = "Nina"; $a[] = "Ophelia"; $a[] = "Petunia"; $a[] = "Amanda"; $a[] = "Raquel"; $a[] = "Cindy"; $a[] = "Doris"; $a[] = "Eve"; $a[] = "Evita"; $a[] = "Sunniva"; $a[] = "Tove"; $a[] = "Unni"; $a[] = "Violet"; $a[] = "Liza"; $a[] = "Elizabeth"; $a[] = "Ellen"; $a[] = "Wenche"; $a[] = "Vicky"; // 从URL获取q参数 $q = $_REQUEST["q"]; $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"; } } } } // 如果未找到提示或输出正确值,则输出“无建议” echo $hint === "" ? "无建议" : $hint;
PHP作为服务端脚本,是一种Web常用的,流行的后端操作脚本。想学习更多的PHP知识,请查看我们的PHP教程