最新的Web开发教程
 

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