使用AJAX根据下拉框返回查询结果

时间:2013-07-21 09:07:27

标签: php sql ajax

我知道这是一个很受欢迎的问题,我已经查看了许多试图了解AJAXjQuery的例子。

我有一个简单的情况,一个下拉框在更改时根据下拉框选择发送AJAX SQL查询结果请求。

页面正确加载,当从下拉框中选择一个部门时,正在调用该函数(警报告诉我),但我没有收到任何返回数据。在尝试识别问题时,如何判断getTeachers.php文件是否实际运行?

网页 在服务器上调用getTeacher.php的脚本

<script src="http://localhost/jquery/jquery.min.js">
</script>
<script>
function checkTeacherList(str) 
{
var xmlhttp;    
if (str=="")
  {
  document.getElementById("txtTeacher").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("txtTeacher").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getTeachers.php?q="+str,true);
xmlhttp.send();
alert(str); //To test it is getting this far, which it does
}
</script>

从服务器返回数据的下拉框和txtTeacher ID

<select name="department_list" id="department_list" onchange="checkTeacherList(this.value);" >  
<?php  
$options[0] = 'All';
$intloop = 1;
while($row = mysql_fetch_array($department_result))
{
$options[$intloop] = $row['departmentName'];
$intloop = $intloop + 1;
}
foreach($options as $value => $caption)  
{  
echo "<option value=\"$caption\">$caption</option>";  
}  
?>  
</select> 

<div id="txtTeachers">Teacher names</div>

服务器端PHP - getTeachers.php

<?php
 $q=$_GET["q"];

 $con = mysql_connect('localhost', 'root', '');
 if (!$con)
   {
   die('Could not connect: ' . mysql_error($con));
   }

 $db_selected = mysql_select_db("iobserve");
 $sql="SELECT * FROM departments WHERE departmentName = '".$q."';";

 $result = mysql_query($sql);

 while($row = mysql_fetch_array($result))
   {
   echo $row['teacherName'];
   }
 mysql_close($con);
 ?> 

3 个答案:

答案 0 :(得分:4)

我记得用Jquery做了第一个Ajax请求,发现很难找到一个好的完整示例,特别是有错误处理的东西(如何在后端告诉用户出现问题,例如数据库不是可用?)。

这是使用PDO和Jquery重写的代码,包括一些错误处理(我没有使用Mysql扩展,因为它是从最近的PHP版本中删除的(顺便说一句,你的代码是开放的SQL注入,很容易丢弃你的数据库) ):

<!DOCTYPE html>
<html>
<head>
    <title>Selectbox Ajax example</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<body>

<div id="error"></div>
<select name="department_list" id="department_list">
    <option value="department1">Department 1</option>
    <option value="department2">Department 2</option>
</select>

<div id="txtTeachers">Teacher names</div>
<div id="result">
    <ul id="list">
    </ul>
</div>

    <script type="text/javascript">

        $(document).ready(function () {

            // if user chooses an option from the select box...
            $("#department_list").change(function () {
                // get selected value from selectbox with id #department_list
                var selectedDepartment = $(this).val();
                $.ajax({

                    url: "getTeachers.php",
                    data: "q=" + selectedDepartment,
                    dataType: "json",

                    // if successful
                    success: function (response, textStatus, jqXHR) {

                        // no teachers found -> an empty array was returned from the backend
                        if (response.teacherNames.length == 0) {
                            $('#result').html("nothing found");
                        }
                        else {
                            // backend returned an array of names
                            var list = $("#list");

                            // remove items from previous searches from the result list
                            $('#list').empty();

                            // append each teachername to the list and wrap in <li>
                            $.each(response.teacherNames, function (i, val) {
                                list.append($("<li>" + val + "</li>"));
                            });
                        }
                    }});
            });


            // if anywhere in our application happens an ajax error,this function will catch it
            // and show an error message to the user
            $(document).ajaxError(function (e, xhr, settings, exception) {
                $("#error").html("<div class='alert alert-warning'> Uups, an error occurred.</div>");
            });

        });

    </script>

</body>
</html>

PHP部分

<?php

// we want that our php scripts sends an http status code of 500 if an exception happened
// the frontend will then call the ajaxError function defined and display an error to the user
function handleException($ex)
{
    header('HTTP/1.1 500 Internal Server Error');
    echo 'Internal error';
}

set_exception_handler('handleException');


// we are using PDO -  easier to use as mysqli and much better than the mysql extension (which will be removed in the next versions of PHP)
try {
    $password = null;
    $db = new PDO('mysql:host=localhost;dbname=iobserve', "root", $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // note the quote thing - this prevents your script from sql injection
    $data = $db->query("SELECT teacherName FROM departments where departmentName = " . $db->quote($_GET["q"]));
    $teacherNames = array();
    foreach ($data as $row) {
        $teacherNames[] = $row["teacherName"];
    }

    // note that we are wrapping everything with json_encode
    print json_encode(array(
            "teacherNames" => $teacherNames,
            "anotherReturnValue" => "just a demo how to return more stuff")
    );

} catch (PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

答案 1 :(得分:1)

将getTeacher.php页面中的查询更改为。 $ sql =“SELECT * FROM departments WHERE departmentName ='$ q'”;

答案 2 :(得分:0)

您需要以单个字符串发送回复。因此,通过查询返回所有教师的字符串。

然后在你的ajax部分中,将此字符串拆分。