用Ajax实现分级联动的例子是比较常用的,此案例用PHP+MysqL+Ajax来实现。首先要导入自己封装好的js文件。然后新建一个html显示的文件
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Ajax实现分类联动</title> <script type="text/javascript" src="public.js"></script> <script> window.onload=function(){ createFirst(); $('kindFirst').onchange=createSecond; }; function createFirst(){ $.get('kind.PHP','cid=0',function(msg){ var length=msg.length; //因为json获取的数据时二维数组 for(var i=0;i<length;i++){ var name=msg[i].name; //获取名字 var id=msg[i].id; //获取ID var op=new Option(name,id); //一般用在动态生成选择项目 $('kindFirst').options.add(op);//把它加载上去 } },'json') } function createSecond(){ var cid=$('kindFirst').value; $.get('kind.PHP','cid='+cid,function(msg){ $('kindSecond').length=0; if($('kindFirst').selectedIndex==0) return; var length=msg.length; for(var i=0;i<length;i++){ var name=msg[i].name; var id=msg[i].id; var op=new Option(name,id); $('kindSecond').options.add(op); } },'json'); } </script> </head> <body> <select id="kindFirst"> <option>请选择</option> </select> <select id="kindSecond"> </select> </body> </html>
<?PHP $cid=$_GET['cid']; $sql="select * from category where cid='$cid' order by id desc"; MysqL_connect('localhost','root','root'); MysqL_select_db('test'); MysqL_query("set names utf8"); $result=MysqL_query($sql); $num=MysqL_num_rows($result); $data=array(); for($i=0;$i<$num;$i++){ $row=MysqL_fetch_assoc($result); $row['name']=iconv('utf-8','utf-8',$row['name']); $data[]=$row; } MysqL_close(); echo json_encode($data); ?>
最后实现的效果如下