PHP Ajax搜索示例

  • PHP Ajax搜索

    搜索界面search.html

    <!DOCTYPE html>
    <html>
    <head>
            <meta charset="UTF-8">
            <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", "php_ajax.php?q=" + str, true);
                    xmlhttp.send();
                }
            }
            </script>
    
    </head>
    <body>
    
    <p><b>搜索您最喜欢的教程:</b></p>
    
    <form>
            <input type = "text" onkeyup = "showHint(this.value)">
    </form>
    
    <p>课程的名字: <span id="txtHint"></span></p>
    
    </body>
    </html>
    
    上面的代码打开一个文件,名字叫做php_ajax.php,使用GET方法,所以我们需要创建一个文件,在同一目录中名为php_ajax.php的名称,将输出将id为txtHint的元素中。

    处理脚本php_ajax.php

    <?php
    // 这些数据在真实的案例中 一般从数据库查询出来
    $a[] = "Android";
    $a[] = "B 语言";
    $a[] = "C 语言";
    $a[] = "D 语言";
    $a[] = "euphoria";
    $a[] = "F#";
    $a[] = "GWT";
    $a[] = "HTML5";
    $a[] = "ibatis";
    $a[] = "Java";
    $a[] = "K 语言";
    $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 === "" ? "请你输入合法的教程名字" : $hint;
    ?>
    
    搜索效果如下图所示