地区三级联动

控制层:

<?php
namespace app\index\controller;

use think\Controller;
use think\Db;

class Addr extends Controller
{
    public function addr(){
        $one = Db::name('global_region') -> where(['parent_id' => 0]) -> select();
        return view('addr',['one'=>$one]);
    }

    public function two(){
        $region_id = input('region_id');
        $two = Db::name('global_region') -> where(['parent_id' => $region_id]) -> select();
        echo json_encode($two);
    }
}
视图层:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<center>
    <form id="form">
        <table>
            <tr>
                <td width="150">
                    国家:<select id="one">
                        <option value="--请选择--">--请选择--</option>
                    {volist name="one" id="vo"}
                    <option value="{$vo.region_id}">{$vo.region_name}</option>
                    {/volist}
                    </select>
                </td>
                <td width="150">
                    省份:<select id="two">
                        <option value="--请选择--">--请选择--</option>

                    </select>
                </td>
                <td width="200">
                    区域、乡、镇:<select id="three">
                    <option value="--请选择--">--请选择--</option>

                </select>
            </td>
            </tr>
        </table>
    </form>
</center>
</body>
</html>
<script src="__STATIC__/jquery-3.3.1.min.js"></script>
<script>
    $('#one').change(function(){
        var region_id = $(this).val();
        $.ajax({
            url:"{:url('addr/two')}",
            data:{region_id:region_id},
            method:"post"
        }).done(function(msg){
            var res = JSON.parse(msg);
            console.log(msg);
            var str = "";
            $.each(res,function (k,v) {
                str += "<option value='"+v.region_id+"'>"+v.region_name+"</option>";
            });
            $('#two').append(str);
        })
    });
    $('#two').change(function(){
        var region_id = $(this).val();
        $.ajax({
            url:"{:url('addr/two')}",
            data:{region_id:region_id},
            method:"post"
        }).done(function(msg){
            var res = JSON.parse(msg);
            // console.log(msg);
            var str = "";
            $.each(res,function (k,v) {
                str += "<option value='"+v.region_id+"'>"+v.region_name+"</option>";
            });
            $('#three').append(str);
        })
    })
</script>

 

posted @ 2022-01-08 17:53  王越666  阅读(40)  评论(0编辑  收藏  举报