省市区三级联动
我的数据表结构是按照级别,省市区都在一张表里面,由父级子级这样出来的
sql
SELECT CONCAT((SELECT b.area_name FROM area_code b WHERE b.id = a.parent_id),’ ‘,a.area_name) FROM area_code a WHERE a.id =’’ concat函数,将两个字符串拼接成一个结果,用来查询市和区的字符串拼接结果,
ajax三级联动查询,后台代码jpa查询省,省的lev=1,去查询,拿到省的id,省的id是市的parent_id,然后再得到区的 id,controller层 @RequestMapping(value="/provinces") @ResponseBody
前端代码 js
function provinces() {
$.get("/provinces", function (data) {
for (i in data)
document.getElementById(“sel_provinces”).add(new Option(data[i].areaName, data[i].id))
})
}
function cities() {
var selection = document.getElementById("sel_provinces");
var index = selection.selectedIndex;
var pId = selection.options[index].value;
$.get("/cities?provinceId=" + pId, function (data) {
$("#sel_cities").empty();
$("#sel_cities").append("<option >请输入城市</option>");
for (i in data)
document.getElementById("sel_cities").add(new Option(data[i].areaName, data[i].id));
})
}
function counties() {
var coun = document.getElementById("sel_cities");
var index = coun.selectedIndex;
var cId = coun.options[index].value;
$.get("/counties?cityId=" + cId, function (data) {
$("#sel_counties").empty();
$("#sel_counties").append("<option >请输入地区</option>");
for (i in data)
document.getElementById("sel_counties").add(new Option(data[i].areaName, data[i].id));
})
}
前端显示省市区的三个联动框
*所在地区:
<select id="sel_provinces" onchange="cities(this)">
<option value="">请输入省份</option>
</select>
<select id="sel_cities" onchange="counties(this)">
<option value="" selected="selected">请输入城市</option>
</select>
<select name="areaCode" id="sel_counties">
<option value="" selected="selected">请输入地区</option>
</select>
后台代码
@RequestMapping(value = “/provinces”)
@ResponseBody
public List getProvinces(){
return locationService.getProvinces();
}
@RequestMapping(value = "/cities")
@ResponseBody
public List<AreaCode> getCities(@RequestParam String provinceId){
return locationService.getCities(provinceId);
}
@RequestMapping(value = "/counties")
@ResponseBody
public List<AreaCode> getCounties(@RequestParam String cityId){
return locationService.getCounties(cityId);
}