1. 程式人生 > >yii框架中省市三級聯動

yii框架中省市三級聯動

檢視層

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>省市三級聯動</title>
</head>
<!-- 因為在框架中,所以是從根目錄下請求的,也就是當前目錄是index.php所在的目錄 -->
<script src="./jquery/jquery.1.12.js"></script>  
<body>
    <form action="">
        <select name="region" id="">
        <option value="0">請選擇...</option>
    <?php foreach ($data as $key => $val): ?>
            <option value="<?= $val['region_id']?>"><?= $val['region_name']?></option>
        
    <?php endforeach ?>
        
        </select>
    </form>
</body>
</html>
<script>
    $(function(){
        $(document).on('change',':input[name="region"]',function(){
            //獲取當前物件select 標籤
            var _this=$(this);
            //獲取值
            var region_id=_this.val();
            //ajax請求的地址
            var url="index.php?r=demo/citylist";

            //清除當前物件變化時,後面的標籤
            _this.nextAll().remove();

            //如果是請選擇就不用請求了
            if(region_id==0){
                return false;
            }

            $.get(url,{'region_id':region_id},function(data){
                //判斷是不是最後一級
                if(data.length==0){
                    return false;
                }

                //拼接字串
                var str='<select name="region"><option value="0">請選擇...</option>';
                $.each(data,function(k,v){
                    str+='<option value='+v.region_id+'>'+v.region_name+'</option>';
                })

                str+='</select>';

                //追加到後面
                _this.after(str);
            },'json');


        })
    })
</script>

控制器層

/**
     * 省市三級聯動
     *
     */
    public function  actionCity(){
        $sql="select * from ecs_region where parent_id='0'";
        $data=yii::$app->db->createCommand($sql)->queryAll();
        return $this->render('city',['data'=>$data]);
    }

    /**
     * 省市三級聯動  ajax請求的方法
     *
     */
    public function actionCitylist(){
        //接值  父id
        $parent_id=yii::$app->request->get('region_id');
        // $parent_id=1;
        $sql="select * from ecs_region where parent_id='$parent_id'";
        $res=yii::$app->db->createCommand($sql)->queryAll();
        // print_r($res);
        return json_encode($res);
        // echo json_encode($res);  也是可以的
    }