根据mysql数据生成二级联动select完整实例

conn.php  //连接文件
<?php
$conn=mysql_connect("127.0.0.1","root","root");
mysql_select_db("test",$conn);
?>

index.php  //前端文件
<?php
include("conn.php");
$id = mysql_fetch_array(mysql_query("select * from gzk where xm10='$pici' order by id asc"));
$name=$id["xm2"];
$dalei=$id["xm1"];
$res = mysql_query("select * from gzk_wuliao where xm1='$dalei' and xm2='$name' order by id asc");
$cities = array(); //一级菜单数组
while ($row = mysql_fetch_assoc($res) )
{
	$cities[$row['id']] = $row['xm3'];
}
?>

大类
<select class="form-control"  style="width: 100%" name="xm3" id="bigname" data-size="false">
	<option selected="selected" value="">-- 请选择大类 --</option>
	<?php foreach ( $cities as $id=>$city ) { ?>
	<option value="<?php echo $city; ?>"><?php echo $city; ?></option>
	<?php } ?>
</select>
小类
<select name="xiaolei" id="xiaolei">
</select>


<script src="jquery-3.4.1.min.js"></script>
<script type="text/javascript">


	function getSelectVal(){
		$.getJSON("ss.php",{dalei:$("#dalei").val()},function(json){
			var xiaolei = $("#xiaolei");
			$("option",xiaolei).remove();
			$.each(json,function(index,array){
				var option = "<option value='"+array['id']+"'>"+array['title']+"";
				xiaolei.append(option);
			});
		});
	}

	$(function(){
		getSelectVal();
		$("#dalei").change(function(){
			getSelectVal();
		});
	});
</script>


ss.php  //后端文件
 <?php
 error_reporting(0);  //这句非常重要,不屏蔽报错就不能正确获得json数据,前端js函数就不能执行完全,之前调试了好久才搞定,坑

 include_once("conn.php");

 $dalei = $_GET["dalei"];
 if(isset($dalei)){
 	$qq=mysql_query("select * from test where iid ='$dalei'");
 	while($row=mysql_fetch_array($qq)){
 		$select[] = array("id"=>$row[id],"title"=>$row[title]);
 	}
 	echo json_encode($select);
 }



 ?>

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读