AJAX 是术语 Asynchronous JavaScript 和 XML 的简称。Ajax 用于构建快速和动态的网页。以下示例演示了使用 AJAX 函数与后端 PHP 脚本的交互,以在网页上提供搜索字段。
第 1 步
将以下脚本另存为 “example.php” −
<html>
<head>
<style>
span {
color: green;
}
</style>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "php_ajax.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>
此代码实质上是一个 HTML 脚本,用于呈现带有文本字段的 HTML 表单。在其 onkeyup 事件中,调用 JavaScript 的 showHint() 函数。该函数将 HTTP GET 请求发送到服务器上的另一个 PHP 脚本。
第 2 步
将以下脚本另存为 “php_ajax.php” −
<?php
// 带名称的数组
$a[] = "Android";
$a[] = "B programming language";
$a[] = "C programming language";
$a[] = "D programming language";
$a[] = "euphoria";
$a[] = "F#";
$a[] = "GWT";
$a[] = "HTML5";
$a[] = "ibatis";
$a[] = "Java";
$a[] = "K programming language";
$a[] = "Lisp";
$a[] = "Microsoft technologies";
$a[] = "Networking";
$a[] = "Open Source";
$a[] = "Prototype";
$a[] = "QC";
$a[] = "Restful web services";
$a[] = "Scrum";
$a[] = "Testing";
$a[] = "UML";
$a[] = "VB Script";
$a[] = "Web Technologies";
$a[] = "Xerox Technology";
$a[] = "YQL";
$a[] = "ZOPL";
$q = $_REQUEST["q"];
$hint = "";
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;
?>
第 3 步
我们将通过输入 URL 在浏览器中打开 example.php 来启动此应用程序 http://localhost/example.php
在搜索字段中的每次击键时,GET 请求都会发送到服务器。服务器脚本从 $_REQUEST 数组中读取字符,并搜索匹配的课程名称。匹配的值显示在浏览器中的文本字段下方。