最新的Web开发教程
 

AJAX PHP实例


AJAX是用来创造更多的交互式应用程序。


AJAX PHP实例

下面的例子将演示如何网页可以同时输入字段的用户类型字符的Web服务器通信:

Start typing a name in the input field below:

First name:

Suggestions:



例子解释:

在上面的例子中,当用户在输入字段的字符,调用函数"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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint").innerHTML = xmlhttp.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占位符和退出的功能。

然而,如果输入字段不为空,执行以下步骤:

  • 创建XMLHttpRequest对象
  • 创建功能被执行时,服务器响应就绪
  • 发送请求开了一个PHP文件(gethint.php)在服务器上
  • 注意, q参数被添加gethint.php?q="+str
  • str变量保存输入字段的内容

PHP文件- "gethint.php"

PHP文件检查名称的数组,并返回相应的name(s)到浏览器:

<?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;
?>