倒霉的大熊

座右铭:天时地利人和

导航

thinkphp5省市区三级联动例子

数据库

数据库下载地址:https://files.cnblogs.com/files/fan-bk/packet_region.zip

php

<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\facade\Request;
class Index extends Controller
{
    public function index()
    {
        if (Request::isPost()) {
            $data = Request::param();
            $id = $data['pro_id'];
            $region = Db::name('packet_region')->where(['parent_id' => $id])->select();

            $opt = '<option>--请选择--</option>';
            foreach($region as $key=>$val){
                $opt .= "<option value='{$val['id']}'>{$val['name']}</option>";
            }
            echo json_encode($opt);
            die;
        }

        $region = Db::name('packet_region')->where(['level_type' => 1])->select();
        $this->assign('region', $region);

		return $this->fetch();
	}

    public function hello($name = 'ThinkPHP5')
    {
        return 'hello,' . $name;
    }
	
	
}

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!-- 省份 -->
<select name="pro" id="pro">
	    <option>--请选择--</option>
    {foreach $region as $vo}
        <option value="{$vo.id}">{$vo.name}</option>
    {/foreach}
</select>


<!-- 城市 -->
<select name="city" id="city">
    <option>--请选择省--</option>
</select>

<!-- 区县 -->
<select name="area" id="area">
    <option>--请选择市--</option>
</select>


<script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
<script>

    $('#pro').change(function(){
        $.ajax({
            type:"post",
            url:"{:url('index/index')}",
            data:'pro_id='+$('#pro').val(),
            dataType:"json",
            success:function(data){
                console.log(data);
                $('#city').html(data);
				$('#area').html('<option>--请选择市--</option>');
            }
        });
    });

    $('#city').change(function(){
        $.ajax({
            type:"post",
            url:"{:url('index/index')}",
            data:'pro_id='+$('#city').val(),
            dataType:"json",
            success:function(data){
                console.log(data);
                $('#area').html(data);
            }
        });
    });
</script>
</body>
</html>

参考:http://www.thinkphp.cn/topic/41905.html

posted on 2018-11-01 17:45  倒霉的大熊  阅读(361)  评论(0编辑  收藏  举报