PHP - AJAX 搜尋



AJAX 是非同步 JavaScript 和 XML 的簡稱。Ajax 用於構建快速且動態的網頁。以下示例演示了與後端 PHP 指令碼的互動,使用 AJAX 函式在網頁上提供搜尋欄位。

步驟 1

將以下指令碼儲存為“example.php” -

<html>
<head>
   <style>
      span {
         color: green;
      }
   </style>
   <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", "hello.php?q=" + str, true);
            xmlhttp.send();
         }
      }
   </script>
</head>
<body>
   <p><b>Search your favourite tutorials:</b></p>
   <form>
      <input type = "text" onkeyup = "showHint(this.value)">
   </form>
   <p>Entered Course name: <span id="txtHint"></span></p>
</body>
</html>

此程式碼本質上是一個 HTML 指令碼,它呈現一個帶有文字欄位的 HTML 表單。在其 **onkeyup** 事件中,呼叫 showHint() JavaScript 函式。該函式向伺服器上的另一個 PHP 指令碼傳送 HTTP GET 請求。

步驟 2

將以下指令碼儲存為“php_ajax.php” -

<?php
   // Array with names
   $a[] = "Android";
   $a[] = "B programming language";
   $a[] = "C programming language";
   $a[] = "D programming language";
   $a[] = "euphoria";
   $a[] = "F#";
   $a[] = "GWT";
   $a[] = "HTML5";
   $a[] = "ibatis";
   $a[] = "Java";
   $a[] = "K programming language";
   $a[] = "Lisp";
   $a[] = "Microsoft technologies";
   $a[] = "Networking";
   $a[] = "Open Source";
   $a[] = "Prototype";
   $a[] = "QC";
   $a[] = "Restful web services";
   $a[] = "Scrum";
   $a[] = "Testing";
   $a[] = "UML";
   $a[] = "VB Script";
   $a[] = "Web Technologies";
   $a[] = "Xerox Technology";
   $a[] = "YQL";
   $a[] = "ZOPL";

   $q = $_REQUEST["q"];
   $hint = "";

   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";
            }
         }
      }
   }
   echo $hint === "" ? "Please enter a valid course name" : $hint;
?>

步驟 3

我們將透過在瀏覽器中開啟 example.php 並輸入 URL **https:///example.php** 來啟動此應用程式。

在搜尋欄位中的每次擊鍵時,都會向伺服器傳送一個 GET 請求。伺服器指令碼從 $_REQUEST 陣列中讀取字元並搜尋匹配的課程名稱。匹配的值顯示在瀏覽器中文字欄位下方。

PHP AJAX Search
廣告