原生的三级联动下拉框
最近在工作中遇到了一个需要三级联动的功能,之前也只用到过地区联动的三级菜单,还是用的插件,这次就不没那么好了,没办法,自己写咯,我下面的写出来的是原生的;写的不好,不要喷我
一共有三个文件,需要引入jquery;分别是,index.php,data.php和get_two.php三个文件,具体代码如下:
index.php:
<?php
include "./data.php";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
</head>
<body>
三级联动下拉框:
<select name="one" id="one">
<option value="">一级选项</option>
<?php foreach($result as $key=>$val): ?>
<?php if($val['level']==1):?>
<option value="<?php echo $val['code_name'];?>"><?php echo $val['name']?></option>
<?php endif;?>
<?endforeach;?>
</select>
<select name="two" id="two">
<option value="">二级选项</option>
</select>
<select name="three" id="three">
<option value="">三级选项</option>
</select>
</body>
</html>
<script type="text/javascript" src="../../public/jquery.min.js"></script>
<script>
$("#one").change(function(){
var id = $(this).val();
if(id){
$.post("./get_two.php",{id:id,level:2},function(data){
if(data){
console.log(data);
html='<option value="all">请选择</option>';
for(var i =0 ;i<data.length;i++){
html+='<option value="'+data[i]['code_name']+'">'+data[i]['name']+'</option>';
}
$("#two").empty();
$("#two").append(html);
}
},'json');
}
})
$("#two").change(function(){
var id = $(this).val();
if(id){
$.post("./get_two.php",{id:id,level:3},function(data){
if(data){
console.log(data);
html='<option value="all">请选择</option>';
for(var i =0 ;i<data.length;i++){
html+='<option value="'+data[i]['code_name']+'">'+data[i]['name']+'</option>';
}
$("#three").empty();
$("#three").append(html);
}
},'json');
}
})
</script>
data.php页面:
<?php
try{
$pdo = new PDO("mysql:host=localhost;dbname=test","root","root");
}
catch(PDOException $e){
echo "数据库连接失败:".$e->getMessage();
exit;
}
$query = "select * from sanji";
$pdostatement = $pdo->query($query);
$result = $pdostatement->fetchAll(PDO::FETCH_ASSOC);
get_two.php页面:
<?php
try{
$pdo = new PDO("mysql:host=localhost;dbname=test","root","root");
}
catch(PDOException $e){
echo "数据库连接失败:".$e->getMessage();
exit;
}
$id = $_POST['id'];
$level = $_POST['level'];
$query = "select * from sanji where level = '$level' and code_name like '$id-%'";
$pdostatement = $pdo->query($query);
$result = $pdostatement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
然后是数据库表:
效果图: