我知道这是一个很受欢迎的问题,我已经查看了许多示例,试图了解 AJAX
和 jQuery
。
我遇到了一种简单的情况,其中一个下拉框在更改时会根据下拉框的选择发送一个 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
<?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 注入(inject)开放,很容易删除数据库) ):
<!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();
}
关于php - 使用AJAX根据下拉框返回查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17770731/