21xrx.com
2024-12-29 01:43:06 Sunday
登录
文章检索 我的文章 写文章
PHP - AJAX和PHP
2021-07-27 12:14:53 深夜i     --     --
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 (this.readyState == 4 && this.status == 200) {
        document.getElementById("txtHint").innerHTML = this.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 action="">
  <label for="fname">First name:</label>
  <input type="text" id="fname" name="fname" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>

 

代码说明:

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

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

  • 创建XMLHTTPRequest对象
  • 创建服务器响应已准备就绪时要执行的函数
  • 将请求发送到服务器上的PHP文件(gethint.php)
  • 请注意,q参数被添加到URL("gethint.php?q ="+ str)
  • str变量包含输入字段的内容

 


PHP文件 - “gethint.php”

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

 

 

  
  
下一篇: php - ajax和mysql

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章