HTML
<select id="top">
<option>顶级分类</option>
{foreach($data as $value)}
<option value="{$value['id']}">{$value['cate_name']}</option>
{/foreach}
</select>
<select id="cate_two">
<option>二级分类</option>
</select>
<select id="cate_three">
<option>三级分类</option>
</select>
JQuery
<script>
//顶级分类与二级分类联动
$('#top').change(function () {
var id = $(this).val();
$('#cate_two').children('option:gt(0)').remove();
$('#cate_three').children('option:gt(0)').remove();
$.ajax({
url: 'duojiTwo?id=' + id,
dataType: 'json',
success: function (res) {
if (res.code !== 200) {
alert(res.msg);
$('#cate_two').children('option:gt(0)').remove();
$('#cate_three').children('option:gt(0)').remove();
}
$.each(res.data, function (index, ele) {
$('#cate_two').append("<option value=" + ele.id + ">" + ele.cate_name + "</option>");
})
}
})
})
//二级分类与三级分类联动
$('#cate_two').change(function () {
var id = $(this).val();
$('#cate_three').children('option:gt(0)').remove();
$.ajax({
url: 'duojiThree?id=' + id,
dataType: 'json',
success: function (res) {
if (res.code !== 200) {
alert(res.msg);
// $('#cate_three').html("<option>" + '三级分类' + "</option>");
$('#cate_three').children('option:gt(0)').remove();
}
$.each(res.data, function (index, ele) {
$('#cate_three').append("<option value=" + ele.id + ">" + ele.cate_name + "</option>");
})
}
})
})
</script>
PHP
public function liandong()
{
$data = Cate::where('pid', '=', 0)->select()->toArray();
return view('/liandong', ['data' => $data]);
}
public function liandongTwo()
{
$id = \request()->get('id');
if (!is_numeric($id)) {
return json([
'code' => 2001,
'msg' => '请先选择顶级分类'
]);
}
$data = Cate::where('pid', '=', $id)->field(['cate_name', 'id'])->select()->toArray();
return json([
'code' => 200,
'msg' => '查找成功',
'data' => $data
]);
}
public function liandongThree()
{
$id = \request()->get('id');
if (!is_numeric($id)) {
return json([
'code' => 2001,
'msg' => '请先选择二级分类'
]);
}
$data = Cate::where('pid', '=', $id)->field(['cate_name', 'id'])->select()->toArray();
return json([
'code' => 200,
'msg' => '查找成功',
'data' => $data
]);
}