首先html加入这3组下拉框,这里有个重点,lay-filter
<div class="layui-input-inline" style="width: 120px;">
<select name="province" id="province" lay-filter="province">
<option value="0">请选择省</option>
<foreach name="province" item="val">
<option value="{$val.id}">{$val.name}</option>
</foreach>
</select>
</div>
<div class="layui-input-inline" style="width: 120px;">
<select name="city" id="city" lay-filter="city">
<option value="0">请选择市</option>
<foreach name="city" item="val">
<option value="{$val.id}">{$val.name}</option>
</foreach>
</select>
</div>
<div class="layui-input-inline" style="width: 120px;">
<select name="area" id="area" lay-filter="area">
<option value="0">请选择县/区</option>
<foreach name="area" item="val">
<option value="{$val.id}">{$val.name}</option>
</foreach>
</select>
</div>
js部分,对下拉框进行监听
layui.config({
base: '/public/static/admin/js/',
version: new Date().getTime() //为了更新 js 缓存,可忽略
}).extend({ //设定模块别名
common: 'common' //如果 common.js 是在根目录,也可以不用设定别名
}).use(['table', 'form', 'common'], function () {...
//监听select选择 省
form.on('select(province)', function(obj){
var cityobj = $('#city');
common.getArea(obj.value,cityobj);
$('#area').empty();
});
//监听select选择 市
form.on('select(city)', function(obj){
var areaobj = $('#area');
common.getArea(obj.value,areaobj);
});
上面数据请求调用了common.js的getArea()函数
/**
* 获取下级区域
*/
getArea: function(value,obj){
var optionHtml = '';
$.get('/index.php?m=Admin&c=Api&a=getRegion&parent_id='+value, function (res) {
if (res.code == 1) {
//替换下拉框的内容
$(obj).empty().html(res.data);
form.render('select');
} else {
return false;
}
});
return optionHtml;
},
调用Api控制器的getRegion()方法
public function getRegion()
{
$parent_id = I('get.parent_id');
$data = M('region2')->where("parent_id=$parent_id")->select();
$html = '<option value=\'\'>选择区域</option>';
if ($data) {
foreach ($data as $h) {
$html .= "<option value='{$h['id']}'>{$h['name']}</option>";
}
}
$this->ajaxReturn(['code'=>1,'msg'=>'操作成功','data'=>$html]);
}
效果演示
最后附上表设计: