目录

AJAX PHP 示例


AJAX 用于创建更具交互性的应用程序。


AJAX PHP 示例

以下示例演示了当用户在输入字段中键入字符时网页如何与 Web 服务器通信:

示例

Start typing a name in the input field below:

Suggestions:

First name:



示例解释

在上面的示例中,当用户在输入字段中键入字符时,调用的函数showHint()被执行。

该功能由以下条件触发onkeyup事件。

这是代码:

示例

<p>Start typing a name in the input field below:</p>
<p>Suggestions: <span id="txtHint"></span></p>

<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>

<script>
function showHint(str) {
  if (str.length == 0) {
    document.getElementById("txtHint").innerHTML = "";
    return;
  } else {
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function() {
      document.getElementById("txtHint").innerHTML = this.responseText;
    }
  xmlhttp.open("GET", "gethint.html?q=" + str);
  xmlhttp.send();
  }
}
</script>
亲自试一试 »

代码解释:

首先,检查输入字段是否为空(str.length == 0)。如果是,则清除 txtHint 占位符的内容并退出该函数。

但是,如果输入字段不为空,请执行以下操作:

  • 创建 XMLHttpRequest 对象
  • 创建当服务器响应准备好时要执行的函数
  • 将请求发送到服务器上的 PHP 文件 (gethint.html)
  • 请注意,添加了 q 参数 gethint.html?q="+str
  • str变量保存输入字段的内容


PHP 文件 - "gethint.html"

PHP 文件检查名称数组,并将相应的名称返回给浏览器:

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