我正在尝试将动态下拉框作为搜索工具,以帮助缩小mysql服务器的显示数据。我是一个体面的PHP程序员,但需要javascript和ajax的帮助。
该网站目前包含3个页面:index_test.php,dropdown.php和dropdown2.php。
在index_test.php上有4个下拉菜单需要填充信息。第一个是在页面加载时使用php从mysql表填充状态名称。第二个框使用引用php代码的.change()填充,并从mysql表中显示处于选定状态的学校。 然后,第三个框应该从第二个框中获取所选值,并将所选学校的类名显示给用户,该步骤是代码中断的位置。 php通过提交表单进行测试时工作,但我希望能够在没有页面刷新的情况下填充最后2个框。 mysql表的格式是: 表学校:( school_id,学校,州) 表类:(class_id,school_id,class_abrv,class_number)
感谢您的帮助
index_test.php的代码:
<?php include_once("connect.php"); ?>
<html>
<head>
<title>ajax</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#state").change(function(){
var state = $("#state").val();
$.ajax({
type:"post",
url:"dropdown.php",
data:"state="+state,
success: function(data) {
$("#school").html(data);
}
});
});
$("#school").change(function(){
var state = $("#school").val();
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+school,
success: function(data) {
$("#classname").html(data);
}
});
});
});
</script>
</head>
<body>
<h1>Get Notes:</h1>
<br/>
<form action="dropdown2.php" method="post">
State: <select id="state" name="state">
<option>--Select State--</option>
<?php
$sql = "SELECT states FROM states";
$result = mysql_query($sql);
while ($output = mysql_fetch_array($result)) {
$state_name = $output['states'];
echo "<option value=\"$state_name\">$state_name</option>";
}
?>
</select>
<br/>
School: <select id="school" name="school">
<option>--Select School--</option>
</select>
<br/>
Class Name: <select id="classname" name="classname">
<option>--Select Class Name--</option>
</select>
<br/>
Class Number: <select id="classnumber" name="classnumber">
<option>Select Class Name</option>
</select>
<br/>
<input type="submit" value="Search" />
</form>
</body>
</html>
Dropdown.php:
<?php
include_once("connect.php");
$state=$_POST["state"];
$result = mysql_query("select schools FROM schools where states='$state' ");
while($school = mysql_fetch_array($result)){
echo"<option value=".$school['schools'].">".$school['schools']."</option>";
}
?>
Dropdown2.php
<?php
include_once("connect.php");
$school=$_POST['school'];
$result = mysql_query("SELECT school_id FROM schools WHERE schools='$school' ");
$school_id = mysql_fetch_array($result);
$id = $school_id['school_id'];
$classname = mysql_query("SELECT DISTINCT class_abrv FROM classes WHERE school_id='$id' ORDER BY class_abrv asc");
while($class = mysql_fetch_array($classname)){
echo"<option value=".$class['class_abrv'].">".$class['class_abrv']."</option>";
}
?>
答案 0 :(得分:0)
在第二个ajax函数中,您已将学校下拉框值分配给状态变量,但是您将变量school传递给ajax帖子。所以没有学校变量就是你得错的原因。
$("#school").change(function(){
var *state* = $("#school").val();
//above variable should be school.
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+*school*,
success: function(data) {
$("#classname").html(data);
}
});
});