最新的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;
?>