JavaScript AJAX PHP

AJAX PHP example
AJAX is used to create more interactive applications.
The following example demonstrates that when a user types characters in the input field, how web pages communicate with the Web server:

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>ajax</title>
<body>
<h2>  XMLHttpRequest 对象 </h2>
<h3>开始在下面的input字段中键入名称:</h3>
<p>建议: <span id="txtHint"></span></p>
<p>First name: <input type="text" id="txt1" onkeyup="showHint(this.value)"></p>
<script>
    function showHint(str) {
        var xhttp;
        if (str.length == 0) {
            document.getElementById("txtHint").innerHTML = "";
            return;
        }
        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xhttp.open("GET", "/jc_script/gethint.php?q="+str, true);
        xhttp.send();
    }
</script>
</body>
</html>

Experience exchange

In the above example, when the user types a character in the input field, The showHint () function is called to perform. This function is triggered by onkeyup event.

Code Description: First, check whether the input field is empty (str.length == 0). If so, please clear the contents txtHint placeholder and exit the function. However, if the input field is not empty, do the following:
create XMLHttpRequest object
to create a server response function is ready to execute
a request is sent to the PHP file (gethint.php) on the server
Note, "gethint.php q? = "+ str added q parameter
str variable save the contents of the input field

PHP files - "gethint.php"
PHP File Checker name of the array, and the corresponding name returned to the browser:

<?php// 带名字的数组
$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";
// 从URL获取q参数
$q = $_REQUEST["q"];
$hint = "";
// 如果$q不等于"",则从数组中查找所有提示
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 === "" ? "无建议" : $hint;

A more detailed article AJAX Tutorial

Guess you like

Origin blog.51cto.com/13578973/2426564