AJAX 用于创建更具交互性的应用程序。
下面的例子演示:当用户在输入字段中键入字符时,网页如何与 web 服务器进行通信:
请在下面的输入字段中键入字母 A-Z:
姓名:
搜索建议:
在上面的例子中,当用户在输入字段中键入字符时,会执行名为 "showHint()" 的函数。
此函数被 onkeyup 事件触发。
下面是 HTML 代码:
<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 占位符的内容并退出函数。
不过,如果输入字段不为空,则进行如下:
这个 PHP 文件检查姓名数组,然后向浏览器返回对应的姓名:
<?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; ?>