easyui省市二级联动

                                easyui省市二级联动
1、[html]
<table cellspacing="15px"><!-- 设置表格每一行的行间距 -->
    <tr>
        <td>所属区域:</td>
        <td>
            <input class="easyui-textbox" type="text" style="width:100px;" id="selfmedia_toutiaouser_province" data-options="required:true"></input><!-- 这里type换成easyui-combobox,请求数据的方法执行了2遍 -->
            <input class="easyui-combobox" type="text" style="width:100px;" id="selfmedia_toutiaouser_city" data-options="required:true"></input>
        </td>
    </tr>
</table>

2、[js]
<script>
    // 省市二级联动
    $('#selfmedia_toutiaouser_province').combobox({  
        valueField:'id', //值字段  
        textField:'name', //显示的字段  
        url:'/selfmedia/toutiao/getprovincecity',  
        panelHeight:'200px',  //下拉选择框的高度,auto自动
        required:true,    //是否必选
        editable:false,//不可编辑,只能选择  
        onChange:function(pid){  
            //$('#selfmedia_toutiaouser_city').combobox('clear');  
            $('#selfmedia_toutiaouser_city').combobox({  
            valueField:'id', //值字段  
            textField:'name', //显示的字段  
            url:'/selfmedia/toutiao/getprovincecity?pid='+pid,  
            panelHeight:'200px',  
            required:true,  
            editable:false,//不可编辑,只能选择  
            //value:'--请选择--'  
            });  
        }
    });
</script>

3、[PHP]
    /**
    * @todo 得到省市信息,
     * 根据参数pid是否存在判断是省还是市
     */
    public function getprovincecityAction(){
        $pid = isset($_GET['pid']) ? (int)$_GET['pid'] : '';
        $where = [];
        $mArea = new AreaModel();
        if($pid){
            $info = $mArea->getOne([['id', $pid]]);
            $type = $info['type'];
            if($type == 3 || $type == 4 ){    //没有市的直接返回自己
                die(json_encode([['id'=>$info['id'],'name'=>$info['name']]]));
            }else{
                $where[] = ['pid', $pid];
            }
        }else{
            $where[] = ['pid', 0];
        }
        
        $areaList = $mArea->getList( $where, 'id,name');
        die(json_encode($areaList));
    }
    
4、[省市数据表结构]
    CREATE TABLE `area` (
      `id` smallint(11) unsigned NOT NULL COMMENT 'id',
      `pid` smallint(3) unsigned NOT NULL COMMENT '父id',
      `name` varchar(20) NOT NULL COMMENT '名称',
      `type` tinyint(1) NOT NULL COMMENT '类型',
      `tel_code` char(5) NOT NULL DEFAULT '' COMMENT '区号',
      `district` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '大区',
      PRIMARY KEY (`id`),
      KEY `pid` (`pid`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='区域表';
    
5、[返回数据示例]
 [{"id":83,"name":"\u957f\u6625"},{"id":84,"name":"\u5409\u6797"},{"id":85,"name":"\u56db\u5e73"},{"id":86,"name":"\u8fbd\u6e90"},{"id":87,"name":"\u901a\u5316"},{"id":88,"name":"\u767d\u5c71"},{"id":89,"name":"\u677e\u539f"},{"id":90,"name":"\u767d\u57ce"},{"id":91,"name":"\u5ef6\u8fb9"}]

猜你喜欢

转载自blog.csdn.net/qq_36025814/article/details/79579432