PHP 实现三级联动
controller 控制器

class San extends Controller
{
function tree()
{
$list = Category::where('pid', 0)->select();
$this->assign('list', $list);
return view();
}
function getTree()
{
$id = input('id');
$getPid= \app\admin\model\San::getPid($id);
return json(['code' => 200, 'msg' => 'success', 'data' => $getPid]);
}
}
view 视图

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<form action="">
<select name="one" id="one">
<option value="">一级</option>
{foreach $list as $v}
<option value="{$v.id}">{$v.cate_name}</option>
{/foreach}
</select>
<select name="two" id="two">
<option value="">二级</option>
</select>
<select name="tree" id="tree">
<option value="">三级</option>
</select>
</form>
</body>
</html>
<script>
$('#one').change(function (){
var id=$('#one').val()
$.ajax({
url:'/san/getTree',
data:{
id:id,
},
type:'POST',
dataType:'JSON',
success:function (e){
console.log(e)
// if(e.code==200){
// var str='<option>二级</option>';
// $.each(e.data,function (i,v){
// str+= '<option value="+v.id+">'+v.cate_name+'</option>';
// })
// $('#two').html(str);
// }
if(e.code==200){
var str = '<option value="">请选择二级分类</option>';
$.each(e.data, function(i,v){
str += '<option value="' + v.id + '">' + v.cate_name + '</option>';
});
$('#two').html(str);
}
},
})
})
$('#two').change(function (){
var id=$('#two').val()
$.ajax({
url:'/san/getTree',
data:{
id:id,
},
type:'POST',
dataType:'JSON',
success:function (e){
console.log(e)
if(e.code==200){
var str='';
str+='<option>二级</option>';
$.each(e.data,function (i,v){
str+= '<option value="+v.id+">'+v.cate_name+'</option>';
})
$('#tree').html(str);
}
// if(e.code==200){
// var str = '<option value="">请选择三级分类</option>';
// $.each(e.data, function(i,v){
// str += '<option value="' + v.id + '">' + v.cate_name + '</option>';
// });
// $('#tree').html(str);
// }
},
})
})
</script>
模型

class San extends Model
{
protected $table='pyg_category';
static function getPid($id){
return self::where('pid',$id)->select();
}
}
路由
\think\Route::get('tree','admin/san/tree');
\think\Route::post('san/getTree','admin/san/getTree');
浙公网安备 33010602011771号