數據庫下載地址:https://files.cnblogs.com/files/fan-bk/packet_region.zipphp
<?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; } }
<!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.htmlcss