W3C中文教程
全球最大最新的中文 Web 技术教程
HTML CSS SQL PHP COLORS MYSQL BOOTSTRAP
 

PHP 与 AJAX



AJAX 被用于创建交互性更强的应用程序。


AJAX PHP 实例

下面的实例将演示当用户在输入框中键入字符时,网页如何与 Web 服务器进行通信:

Example

尝试在输入框中输入一个名字:

First name:

Suggestions:


实例解析

当用户在上面的输入框中键入字符时,会执行 "showHint()" 函数。

该函数由 "onkeyup" 事件触发:

以下是HTML代码:

Example

<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>
运行实例 »

代码解析:

如果输入框是空的(str.length==0),该函数会清空 txtHint 占位符的内容,并退出该函数。

如果输入框不是空的,那么 showHint() 会执行以下步骤:

  • 创建 XMLHttpRequest 对象
  • 创建在服务器响应就绪时执行的函数
  • 发送请求到服务器上的PHP文件(gethint.php)
  • 请注意添加到 url 末端的参数 q (gethint.php?q="+str)
  • 并且 str 变量获取输入框中的内容

PHP文件 - "gethint.php"

PHP文件检查数组中的名称,并将相应的名称返回到浏览器:

<?php
// Array with names
$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";

// get the q parameter from URL
$q = $_REQUEST["q"];

$hint = "";

// lookup all hints from array if $q is different from ""
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";
            }
        }
    }
}

// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>