练习,就当练习。
省市区三级联动,样式如下图所示:
1,导入两个js文件并且导入数据库文件。
两个js文件分别是jquery-2.1.4.min.js和jquery-1.js,数据库文件,见附件。
2,建一个index.html
<div> <label>所在地点</label> <select name="province_id" id="province_id" style="width:150px;"> <option>请选择</option> <volist name="province_list" id="province"> <option value="{$province.region_id}">{$province.region_name}</option> </volist> </select> <select name="city_id" id="city_id" style="width:150px;" > <option>请选择</option> <volist name="city_list" id="city"> <option value="{$city.region_id}" selected="selected">{$city.region_name}</option> </volist> </select> <select name="district_id" id="district_id" style="width:150px;" > <option value="0">请选择</option> <volist name="dis_list" id="dis"> <option value="{$dis.region_id}" selected="selected">{$dis.region_name}</option> </volist> </select> </div>
写ajax啦,一个是获取市,一个是获取县区。
<script> $("#province_id").change(function(){ var province_id=$(this).val(); $.ajax({ url:‘/city/index.php/Home/Index/get_citys‘, Type:"POST", data:"province_id="+province_id, dataType:"json", success:function(data){ var city = data.city; var option=$("<option></option>"); $(option).val("0"); $(option).html("请选择"); var option1=$("<option></option>"); $(option1).val("0"); $(option1).html("请选择"); $("#city_id").html(option); $("#district_id").html(option1); for(var i in city){ var option=$("<option></option>"); $(option).val(city[i][‘region_id‘]); $(option).html(city[i][‘region_name‘]); $("#city_id").append(option); } } }); }); </script> <script> $("#city_id").change(function(){ var city_id=$(this).val(); $.ajax({ url:‘/city/index.php/Home/Index/get_district‘, Type:"POST", data:"city_id="+city_id, dataType:"json", success:function(data){ var district = data.district; var option=$("<option></option>"); $(option).val("0"); $(option).html("请选择"); $("#district_id").html(option); for(var i in district){ var option=$("<option></option>"); $(option).val(district[i][‘region_id‘]); $(option).html(district[i][‘region_name‘]); $("#district_id").append(option); } } }); }); </script>
2,后台代码很重要。
<?php namespace Home\Controller; use Think\Controller; class IndexController extends Controller { //获取省和直辖市 public function index(){ $listObj = M(‘region‘); $whereprovince[‘top_parentid‘] = 0; $listprovince = $listObj->where($whereprovince)->select(); $this->assign("province_list",$listprovince); $this->display(); } //获取地级市 public function get_citys(){ $listObj = M(‘region‘); $where[‘top_parentid‘] = I(‘province_id‘); $where[‘level‘] = 2; $list = $listObj->where($where)->select(); $data=array(‘status‘=>0,‘city‘=>$list); header("Content-type: application/json"); exit(json_encode($data)); } //获取地级县 public function get_district(){ $listObj = M(‘region‘); $where[‘parent_id‘] = I(‘city_id‘); $where[‘level‘] = 3; $list = $listObj->where($where)->select(); $data=array(‘status‘=>0,‘district‘=>$list); header("Content-type: application/json"); exit(json_encode($data)); }
下面是核心代码和数据库文件,需要的下载就可以了。
http://pan.baidu.com/s/1kU2RDTP
时间: 2024-10-14 04:29:16