PHP+MySQL实现二级联动下拉列表
1.Javascript在下拉列表的各个对象
2.案例代码
Liandong.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP二级联动测试</title>
</head>
<body>
<?php
$link=mysql_connect("localhost","root","12345678") or die("Could not connect:".mysql_error());
mysql_select_db("phpquery") or die("Could not select database or database haven't created");
//获取大类别
$queryCol="select*from tb_firstcategory order by id";
mysql_query("set names utf-8");
$result1=mysql_query($queryCol) or die("Query failed:".mysql_error());
$firstcategories=array();
while($row1=mysql_fetch_array($result1)){
$firstcategories[]=$row1;
}
mysql_free_result($result1);
//获取小类别
$querySecondCat="select*from tb_secondcategory order by fid desc";
mysql_query("set names utf-8");
if(!($result2=mysql_query($querySecondCat))){
die("Cound not query tb_secondcategory list");
}
$secondcategories=array();
while($row2=mysql_fetch_array($result2)){
$secondcategories[]=$row2;
}
mysql_free_result($result2);
?>
<script language="javascript">
var secondcategoryCount;
//存储小类别的数据
form_secondcategory=new Array();
<?php
$num2=count($secondcategories); //获取小类别表中记录的个数?>
secondcategoryCount=<?php echo $num2;?>;
<?php
for($j=0;$j<$num2;$j++){ //从0开始取出上面小类别数据填充的数组
?>
form_secondcategory[<?php echo $j;?>]=new Array("<?php echo $secondcategories[$j]['id'];?>","<?php echo $secondcategories[$j]['fid'];?>","<?php echo $secondcategories[$j]['categoryname'];?>");
<?php } ?>
function changeFirstCate(fid){
document.form1.secondcategory.length=0;
var id=id;
var j;
for(j=0;j<secondcategoryCount;j++){
if(form_secondcategory[j][1]==fid){ //fid等于大类别的id document.form1.secondcategory.options[document.form1.secondcategory.length]=n ew Option(form_secondcategory[j][2],form_secondcategory[j][0]);
}else{
document.form1.secondcategory.options[0]=new Option('==选择小类别==',""); //label的value为空’’
}
}
}
//获取选中的列表文本
function getCategory(){
var first=document.getElementById("firstcategory");
var index=first.selectedIndex;
var second=document.getElementById("secondcategory");
var index1=second.selectedIndex;
alert(first.options[index].text+second.options[index1].text);
}
</script>
<form name="form1" method="post">
选择:<select id="firstcategory" name="firstcategory" onchange="changeFirstCate(document.form1.firstcategory.options[document.form1. firstcategory.selectedIndex].value)" size="1">
<option selected>==请选择大类别==</option>
<?php
$num=count($firstcategories);
for($i=0;$i<$num;$i++){
?>
<option value="<?php echo $firstcategories[$i]['id'];?>"><?php echo $firstcategories[$i]['categoryname'];?></option>
<?php
}
?>
</select>
<select id="secondcategory" name="secondcategory">
<option selected value="">==选择小类别==</option>
</select>
<input type="button" name="submit" value="提交" onclick="getCategory();"/>
</form>
<div id="rel" style="display:none;"></div>
</body>
</html>。