javascript - PHP、AJAX 和 MySQL 集成

标签 javascript php mysql ajax dom-events

我正在尝试让下面的代码正常工作,以便它调用一个 JS 函数将一个值传递到我的 PHP 文件,该文件将从 MySQL 数据库返回多个值。这是我认为非常简单的作业的一部分,但我认为我的问题在于 JavaScript 事件处理程序 - 如何引用输入值?

HTML:

<form>
   <input type="text" name="users" onkeydown="showUser(this)"/>
</form>
        
<div id="txtHint">
    <p id="responder"><b>Person info will be listed here.</b></p>
</div>

showUser() 函数:

<script type="text/javascript">
        function showUser(str)
        {
        if (str=="")
            {
            document.getElementById("responder").innerHTML="";
            return;
            } 
        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("responder").innerHTML=xmlhttp.responseText;
                }
            }
        xmlhttp.open("GET","php/student_query.php?q="+str,true);
        xmlhttp.send();
        }
    </script>

PHP:

<?php
$q=$_GET["q"];
// Step 1
$conn = mysql_connect("localhost", "root");
// Step 2
mysql_select_db("collegeData", $conn);
//Step 3

$sql="SELECT * FROM studenttable WHERE studentID = '".$q."'";
$result = mysql_query($sql);

// Step 4
while ($row = mysql_fetch_array($result))
{
// Step 5
echo "Hello $row[firstName] $row[lastName]<br/>";
echo "Your two course modules are $row[moduleNo1] and $row[moduleNo2]<br/>";
echo "<tr><td> $row[firstName]</td><td> $row[lastName] </td> <td> $row[studentID] </td> </tr>";
echo "<br/>";
}
// Step 6
mysql_close($conn);
?>

就像我说的,我认为我的问题出在事件处理程序中,我不太擅长 JS。如果有任何帮助,我将不胜感激。

最佳答案

看起来您正在将输入元素发送到您的函数,而不是它的值。尝试

<input type="text" name="users" onkeydown="showUser(this.value);" />

此外,您应该通过将 PHP 更改为来保护您的数据库查询不 protected

$q = mysql_real_escape_string(trim($_GET["q"]));
if($q == "")
{
    echo "";
    exit;
}

关于javascript - PHP、AJAX 和 MySQL 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9539174/

相关文章:

JavaScript 正则表达式重复(子)组

javascript - AngularJSJ - Uncaught Error : [$injector:modulerr] (chrome console error)

php - 如何在 php 中显示第一个条目的最后一个条目?

php - Laravel 队列和跨类的持久变量

php - 如何以及在何处设置和检查 group_concat_max_len

javascript - 延迟 promise - 如果回调不符合条件,则重新发送相同的请求

javascript - 如何使用 phantomjs 呈现 html 元素

PHP setcookie() 问题

mysql replication undo change master on master host

mysql - 不断收到与数据库的失败连接