Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 基于下拉框使用AJAX返回查询结果_Php_Sql_Ajax - Fatal编程技术网

Php 基于下拉框使用AJAX返回查询结果

Php 基于下拉框使用AJAX返回查询结果,php,sql,ajax,Php,Sql,Ajax,我知道这是一个很受欢迎的问题,我已经看过很多例子试图了解AJAX和jQuery 我有一个简单的情况,当change根据下拉框选择发送AJAX请求以获取SQL查询结果时,会有一个下拉框 当从下拉框中选择某个部门时,页面正确加载并调用函数。警报告诉我,但我没有收到任何返回数据。在试图识别问题时,我如何判断getTeachers.php文件是否正在实际运行 网页 用于在服务器上调用getTeacher.php的脚本 <script src="http://localhost/jquery/jqu

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

我有一个简单的情况,当change根据下拉框选择发送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>
用于从服务器返回数据的下拉框和TXT教师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


将getTeacher.php页面中的查询更改为。
$sql=从部门名称为“$q”的部门中选择*

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

您需要以单个字符串发送响应。因此,创建一个查询返回的所有教师的字符串


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

为了测试文件是否运行,您可以使用一些硬编码的虚拟数据来响应,而不是运行可能失败的代码。谢谢-结果证明,我需要将完整路径放入php文件。我在WordPress上运行它,它一定很难找到它。如果您不希望每个人都可以删除您的数据库,请将mysql\u real\u escape\u字符串添加到您的select查询中。谢谢-问题是缺少分号。。。。。部门名称='.$q.';;首先,我非常感谢你花了这么多时间回答这个问题。我同意刚开始时很难找到好的例子。事实上,我已经让它工作起来了,并且似乎对它有了更好的理解,但我会仔细检查您发送的内容以进一步改进它。我很想知道什么是SQL注入,但我也会查一下。我知道我需要离开MySQL。。。要学的东西太多了。再次感谢。
<?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();
}