您的位置:首页 > 编程语言 > Java开发

Spring MVC+JSP实现三级联动

2015-11-25 18:54 597 查看
jsp代码

<script type="text/javascript">
$(function() {
initProvinces();
});
/**
* 获取省列表
*/
function initProvinces() {
$('#province').empty();
$.ajax({
type : "POST",
url : basePath + "district/getProvinces.do",
success : function(data) {
$.each(data, function(i, it) {
$("<option value='" + it.id + "' />"
+ it.name + "<br>").click(function() {
initCities(it.id);
}).appendTo($('#province'));
});
}
});
}
/**
* 获取市列表
*/
function initCities(provinceID) {
$('#city').empty();
$.ajax({
type : "POST",
url : basePath + "district/getCities.do?province=" + provinceID,
success : function(data) {
$.each(data, function(i, it) {
$("<option value='" + it.id + "' />"
+ it.name + "<br>").click(function() {
initCounties(it.id);
}).appendTo($('#province'));
});
}
});
}
/**
* 获取区县列表
*/
function initCounties(cityID) {
$('#county').empty();
$.ajax({
type : "POST",
url : basePath + "district/getCounties.do?city=" + cityID,
success : function(data) {
$.each(data, function(i, it) {
$("<option value='" + it.id + "' />"
+ it.name + "<br>")
.appendTo($('#province'));
});
}
});
}
//……
</script>
<body>
选择地区:
<select id='province'><option>---省---</option></select>
<select id='city'><option>---市---</option></select>
<select id='county'><option>---区---</option></select>
</body>
spring MVC 代码:

@Controller
@RequestMapping(value = "/district")
public class districtController {
@Resource
private DistrictService districtService;
/**
* 获取省列表
* @return
* @throws Exception
*/
@RequestMapping(value = "getProvinces")
@ResponseBody
public Object getProvinces() throws Exception {
return districtService.getProvinces();
}
/**
* 获取市列表
* @param province
* @return
* @throws Exception
*/
@RequestMapping(value = "getCities")
@ResponseBody
public Object getCities(@RequestParam(value = "province") String province) throws Exception {
return districtService.getCities();
}
// 再往下级的获取方式和getCities方法都相同,所以此处略过
}


3个select。 第一个select的option是写到页面的或者jsp标签。然后给这个select的change绑定事件,让这个事件去加载第二个select的option。同样,给第二个select也绑定一个change事件去加载第三个select的数据。

//绑定事件
$("#select1").live(change,function(){
$.ajax({
url:aaaa,//提交的地址
data:{
select1id:$("#select1").val();
}
type:'post',
datatype:'json',
success:function(return){
$("#select2 option").remove();//清空原来的选项
for(var i=0;i<return.length;i++)
{
$("#select2").append("<option val='"+return[i].value+"'> "+return[i].name+"</option>")
}
}
})
})


@requestMapping("/")
@responseBody
public List<City> getCitysByErea(String ereaid,HttpServletRequest request,HttpServletResponse response){
List<City> citys =cityService.getXXX(erarid);
return citys;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: