为了减轻数据库压力,采用逐层异步请求+缓存方式来优化性能。
前端采用字符串拼接+字符串模板方式逐步请求。
源码包括全国省市区数据库+基于tp的控制器+前端页面
github托管地址:https://github.com/sunjdk/three-level.git
public function index(){
//$this->show('thinkphp');
$db=M('provinces');
$result=S('result');
if(!$result){
$result=$db->select();
//p($result);
S('result',$result,30);
}
$this->assign('province',$result);
$this->display();
}
public function getCity(){
$proID=I('provinceid');
if(IS_AJAX){
///p($proID);
$db=M('cities');
$where=array('provinceid'=>$proID);
$city=$db->where($where)->select();
//p($city);
/**
* 返回类型有三种情况
* 1.北上津 等直辖市 返回市辖区
* 2.港澳台 返回空
* 3.正常的地级市
*/
if($city){
$this->ajaxReturn($city);
}
}else{
$this->error('非法请求');
}
}
public function getArea(){
$citID=I('cityid');
if(IS_AJAX){
//p($citID);
$db=M('areas');
$where=array('cityid'=>$citID);
$area=$db->where($where)->select();
if($area){
$this->ajaxReturn($area);
}
}else{
$this->error('非法请求');
}
}
演示效果:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>三级联动的地区</title>
<style>
ul,li{list-style-type:none}
a{color:#444;text-decoration: none;}a:hover{color:blue}
</style>
</head>
<body>
<div class="header">中国省市区三级联动</div>
<div class="content">
<div class="con">
<div class="left">
<ul>
<foreach name="province" item="vo">
<li><a href="javascript:;" onclick="getCity(this)" id={$vo.provinceid}>{$vo.province}</a></li>
</foreach>
</ul>
</div>
<div class="right"></div>
</div>
</div>
<div class="footer"></div>
<JS file="__PUBLIC__/node_modules/jquery/dist/jquery.min.js"/>
<script>
var cityUrl="{:U('getCity')}",
areaUrl="{:U(getArea)}";
function getCity(obj){
var provinceid=obj.getAttribute("id");
$.get(cityUrl,{'provinceid':provinceid},function(res){
var str="<ul>";
$.each(res,function(index,item){
str+=`<li><a href="javascript:;" id="${item.cityid}" onclick="getArea(this)">${item.city}</a></li>`;
console.log(res);
})
str+="</ul>";
console.log(str);
//alert(str);
$('#'+provinceid).parent().after(str);
})
}
function getArea(obj){
var cityid=obj.getAttribute('id');
$.get(areaUrl,{'cityid':cityid},function(res){
var str="<ul>";
$.each(res,function(index,item){ // $(".index-main ul").append(`<li>${basket.onSale}</li>`)
str+=`<li><a href="javascript:;" id="${item.areaid}" onclick="getCity(this)">${item.area}</a></li>`;
console.log(res);
});
str+="</ul>";
console.log(res);
//alert(str);
$('#'+cityid).parent().after(str);
})
}
</script>
</body>
</html>