我知道这是一个很受欢迎的问题,我已经看过很多例子试图让我的头脑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>
用于从服务器返回数据的下拉框和 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);
?>