2

我知道这是一个很受欢迎的问题,我已经看过很多例子试图让我的头脑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);
 ?> 
4

3 回答 3

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();
}
于 2013-07-21T11:45:22.163 回答
1

将您在 getTeacher.php 页面中的查询更改为。$sql="SELECT * FROM 部门 WHERE 部门名称 = '$q'";

于 2013-07-21T09:13:03.520 回答
0

您需要在单个字符串中发送您的响应。因此,将查询返回的所有教师组成一个字符串。

然后在你的 ajax 部分,拆分这个字符串。

于 2013-07-21T11:49:17.287 回答