ajax、php和mysql连接问题

ajax, php and mysql connection issues

本文关键字:连接 问题 mysql php ajax      更新时间:2023-09-26

Am使用ajax从数据库中获取数据,但失败了。数据应该显示在我在名为"display"的主页面中声明的div中。查询运行,但div上没有打印任何内容。以下是我的代码:

//ajax:
<script>
function Jobs(str) {
    if (str == "") {
        document.getElementById("display").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = 
        function  () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("display").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("POST","search.php?q="+str);
        xmlhttp.send();
    }
}
</script>
//php
?php $q = intval($_GET['q']);?>
<?php
    include('includes/conn.php');
    $row="SELECT DISTINCT title,id FROM jobs  WHERE dept='$q' AND state=0 ORDER BY id";
    $query=mysqli_query($conn,$row) or die(mysqli_error($conn));
    while($row=mysqli_fetch_array($query))
    {
        echo $row['title'];
    }
    mysqli_close($conn);
    ?>

示例ajax示例代码

addfield.php文件:

<html>
    <head>
    <script>
    function Jobs(str) {
        if (str == "") {
            document.getElementById("display").innerHTML = "";
            return;
        } else {
            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else {
                // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = 
            function  () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("display").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("POST","search.php?q="+str);
            xmlhttp.send();
        }
    }
    </script>
    </head>
    <body>
    <p><b>Start typing a name in the input field below:</b></p>
    <form> 
    First name: <input type="text" onkeyup="Jobs(this.value)">
    </form>
    <p>Suggestions: <span id="display"></span></p>
    </body>
    </html>

search.php代码:

<?php
echo $q = $_REQUEST["q"];
?>