Layui的省市区三级联动

PHP:
/**
* 通过接口获取省市区
* @param string $name
* @return json
*/

public function getDataTree($name = '')
{
    try {

        if (!empty($name)) {

            $info = M("region")->field('id')->where(['name ' => $name])->find();

            if (!empty($info)) {

                $list = M("region")->field('name')->where('pid =' . $info['id'])->order('id asc')->select();

            }


        }

        die(json_encode($list));


    } catch (Exception $e) {
        $this->error($e->getMessage(),'',true);
    }
}

HTML:

                <select name="province" id="province" lay-verify="required" lay-filter="province" lay-search >
                    <option value="">--请选择或搜索--</option>
                    <option value="{$info.province}" selected>{$info.province}</option>
                </select>
                <select name="city" id="city" lay-verify="required"  lay-filter="city" lay-search >
                    <option value="">--请选择或搜索--</option>
                    <option value="{$info.city}" selected>{$info.city}</option>
                </select>
				 <select name="area" id="area" lay-verify="required"  lay-filter="area" lay-search >
                    <option value="">--请选择或搜索--</option>
                    <option value="{$info.area}" selected>{$info.area}</option>
                </select>

JavaScript:

  function getArea(id,value){
        $.ajax({
            url: "{:U('getDataTree')}",
            data: { name: value },
            async: false,
            dataType: 'json',
            type: 'POST',
            success: function (res, textStatus, jqXHR) {
               if(value!='中国'){
                   $('#'+id).empty();
               }
                res.forEach(function(item, index){
                    $('#'+id).append(new Option(item.name, item.name));

                });
                form.render('select'); //加载select
            }
        })
    }

    //页面一打开就执行
    layer.ready(function(){
        getArea('province','中国');
    });
	
    //取得市级
    form.on('select(province)',function(data){
        getArea('city',data.value);

    })
	
    //取得区/县级
    form.on('select(city)',function(data){
        getArea('area',data.value);

    })

其中,new option()的方法借鉴自同事生哥的代码。

原文地址:https://www.cnblogs.com/ccdv/p/12867133.html