微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我知道这是一个很受欢迎的问题,我已经看过很多试图让我了解AJAX和jQuery的例子.

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

页面正确加载,并在从下拉框中选择部门时调用函数(警报告诉我)但我没有收到任何返回数据.在尝试识别问题时,如何判断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);
 ?> 

解决方法:

我记得用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();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐