省市县三级联动是web开发中常用的功能,网上有很多实现的方法,笔者在这也提供一中ajax实现的方法(后台java处理)。
现在使用light7写手机的前台页面,以前的省市区不能完美运行,现在这个可以在light7框架中完美运行,其实还可以优化,有时间再来优化
html代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
<title>省市县title>
<style>
.box{margin-left:20px;margin-top: 20px;width: 300px;height: 200px;border: 1px dashed black; }
h2{text-align: center;}
span{font-size:20px;width: 66px;height: 30px;margin-left: 20px;display: inline-block;}
select{width: 100px;height: 30px;font-size:16px;}
.sub{margin-left: 200px;margin-top: 5px; width: 70px;height: 30px;font-size:20px; line-height: 20px; background-color: rgb(49, 159, 229);color: white;border-radius: 3px;border: none;}
style>
<script src="js/jquery.js">script>
head>
<body>
<div class='box'>
<h2>省市县/区三级联动h2>
<form id="pcc" action="action.php" method="POST">
<span>省 :span>
<select id="pro" name="pro">
select><br/>
<span>市 :span>
<select id="city" name="city">
select><br/>
<span>县/区:span>
<select id="county" name="county">
select><br/>
<input class="sub" type="submit" value="提交" >
form>
div>
<script>
$(function(){
$.ajax({
type:"POST",
cache:false,
url:"location/listJson.do",
data:{"pid":0},
dataType:"json",
success:function(data){
var option='';
$.each(data.obj,function(n,value){
option += '+n.areaname+'';
})
$("#pro").append(option);
}
});
$("#pro").change(function(){
var pid=$(this).val();
$.ajax({
type:"POST",
cache:false,
url:"location/listJson.do",
data:{"pid":pid},
dataType:"json",
success:function(data){
//追加本机option前,先清除city和county的option,以免重选时干扰
$("#city option").remove();
$("#county option").remove();
var option='';
$.each(data.obj,function(n,value){
option += '+n.areaname+'';
})
$("#city").append(option);
}
});
});
$("#city").change(function(){
var pid=$(this).val();
$.ajax({
type:"POST",
cache:false,
url:"location/listJson.do",
data:{"pid":pid},
dataType:"json",
success:function(data){
//同上
$("#county option").remove();
var option='';
$.each(data.obj,function(n,value){
option += '+n.areaname+'';
})
$("#county").append(option);
}
});
});
})
script>
body>
html>
如上所示,本文将选项
都放在ajax请求里,ajax请求每次提供pid(初始值为0,即顶级id),返回两个参数,本级id和父级pid;通过chang事件追加需要提供的
。
java代码如下:
java的controller层代码如下:
@RequestMapping(value="/listJson")
@ResponseBody
public Json getLocationList()throws Exception{
PageData pd = new PageData();
pd = this.getPageData();
List locationList = locationService.listAll(pd.get("PARENTID").toString());
if (locationList!=null){
return new Json(true,"success",locationList);
} else {
return new Json(false,"fail",null);
}
}