JQUERY+PHP实现二级下拉选项
转其它高手的写法,不是原创,不适用LAYUI,我也是在LAYUI里调试了半天都没有成功
<?php include 'inc/config.inc.php'; include 'inc/mysql.inc.php'; $link=connect(); $query="select * from college"; $res=execute($link,$query); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script> <link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <title>Document</title> </head> <body> <script> $(function(){ getSelectVal(); $("#college_id").change(function(){ getSelectVal(); }); }); </script> <form class="form-horizontal"> <label class="col-sm-2 control-label">学院</label> <div class="col-sm-10"> <select name="college_id" id="college_id" class="form-control"> <?php while($row=mysqli_fetch_assoc($res)){ echo '<option value="'.$row['id'].'">'.$row['college_name'].'</option> '; } ?> </select> </div> <label class="col-sm-2 control-label">教师</label> <div class="col-sm-10"> <select name="teach_id" id="teach_id" class="form-control"> </select> </div> </form> <script> function getSelectVal(){ $.getJSON("time.php",{college_id:$("#college_id").val()},function(json){ var teach_id = $("#teach_id"); $("option",teach_id).remove(); //清空原有的选项 $.each(json,function(index,array){ var option = "<option value='"+array['id']+"'>"+array['teach_name']+"</option>"; teach_id.append(option); }); }); } </script> </body> </html>
time.php
<?php include 'inc/config.inc.php'; include 'inc/mysql.inc.php'; $link=connect(); $college_id=$_GET['college_id']; $query="select * from teach where college_id={$college_id}"; $res=execute($link,$query); while($rows=mysqli_fetch_array($res)){ $select[]=array("id"=>$rows['id'],"teach_name"=>urlencode($rows['teach_name'])); } echo urldecode(json_encode($select)); ?>