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