數據表省市區三級聯動
在工作中,老是會遇到地址三級關聯,公司(外包)給了要求是能使用插件的絕不要自己寫,美其名曰:不要重復造輪子。我的想法是:你得知道輪子是怎么造的,才不去做重復性肉雞行為。
所以自己就寫了一個。
sql國家地址表:http://pan.baidu.com/s/1gfslGkV
用到的東西:jquery,php,thinkphp框架和一張國家地區表
前台模板頁面 index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="//cdn.bootcss.com/jquery/1.12.2/jquery.min.js"></script>
<title>登陸測試</title>
</head>
<body>
<select name="sheng" id="sheng">
<option value="請選擇所在省份">請選擇所在省份</option>
<volist name="sheng" id="vo1">
<option value="{$vo1.region_id}" id="sheng">{$vo1.region_name}</option>
</volist>
</select>
<select name="city" id="city" style="display: none;">
</select>
<select name="xian" id="xian" style="display: none;">
</select>
<script>
$(function () {
$('#sheng').change(function () {
//省份更改后,城市,縣城的情況都要被全部更新(先清除,再添加)
$("#city").css('display','none');
$("#city").children().remove(); //去除原來的城市列表
$("#xian").css('display','none');
$("#xian").children().remove(); //去除原來的縣級列表
var value = this.value; //獲取省份value作為城市的parent_id
var url = '__CONTROLLER__/region';
$.ajax({ //jquery ajax
type:'post',
url:url,
data:{'value':value},
success:function (data) {
var result = JSON.parse(data);
//為了防止直轄市情況下,change條件無法觸發
$("#city").append("<option value='請選擇所在城市'>請選擇所在城市</option>");
for(var i = 0;i < result.length;i ++){
/*循環添加所有城市列表*/
$("#city").append("<option value='"+result[i].region_id+"'>"+result[i].region_name+"</option>");
$("#city").css('display','inline');
}
}
});
});
/*同上*/
$('#city').change(function () {
//城市更改后,更新縣級數據
$("#xian").css('display','none');
$("#xian").children().remove();
//這里的value不要和上面的重復,否則變量提升機制會覆蓋掉前面的變量值
var valueCity = this.value;
var urlCity = '__CONTROLLER__/region';
$.ajax({
type:'post',
url:urlCity,
data:{'value':valueCity},
success:function (data) {
var result = JSON.parse(data);
for(var i = 0;i < result.length;i ++){
/*alert(result[i].region_id + ' '+result[i].region_name);*/
$("#xian").append("<option value='"+result[i].region_id+"'>"+result[i].region_name+"</option>");
$("#xian").css('display','inline');
}
}
})
});
});
</script>
</body>
</html>
后台是使用的thinkphp框架
<?php
namespace Home\Controller;
use Think\Controller;
class RegionController extends Controller
{
public function index(){
$region = M('region');
$condition['parent_id'] = 1;
$sheng = $region->where($condition)->select();
$this->assign('sheng',$sheng);
$this->display();
}
public function region(){
if (IS_AJAX){
$region = M('region');
$condition['parent_id'] = $_POST['value'];
$city = $region->where($condition)->select();
echo json_encode($city);
}
}
}
這樣就實現了三級聯動,希望自己以后,不要成為碼農,要懂得思考。