1、前端HTML代码
<div class="layui-form-item">
<label for="level1" class="layui-form-label">
<span class="x-red">*</span>商品一级分类</label>
<div class="layui-input-inline">
<select id="level1" name="level1" class="valid" lay-filter="level1">
<option value="0">请选择</option>
{foreach $level1 as $v}
<option value="{$v.id}">{$v.cate_name}</option>
{/foreach}
</select>
</div>
<div class="layui-input-inline">
<select id="level2" name="level2" class="valid" lay-filter="level2">
</select>
</div>
<div class="layui-input-inline">
<select id="level3" name="cate_id" class="valid">
</select>
</div>
</div>
2、前端JS代码
function changeCate(args1,args2){
form.on('select('+args1+')',function (data) {
// 获取一级分类id
var id = data.value;
if(id == 0){
$("#"+args2).html("");
form.render();
return false;
}
// 根据一级分类id 查询二级分类
$.get("{:url('getSon')}",{id:id},function (data) {
var str = "<option value='0'>请选择</option>";
for(var i=0;i<data.sons.length;i++){
str += "<option value='"+data.sons[i].id+"'>"+data.sons[i].cate_name+"</option>";
}
$("#"+args2).html(str);
form.render();
},"json");
});
}
changeCate('level1','level2');
changeCate('level2','level3');
3、后端PHP代码
public function create(){
// 获取一级分类
$level1 = Db::name("category")->where("pid",0)->order("id")->select();
$data = compact("level1");
return view("",$data);
}
// 获取二级分类
public function getSon($id){
$data['sons'] = Db::name("category")->where(["pid"=>$id])->select();
$data['sql'] = Db::getLastSql();
return json($data);
}