1.先导入3个jar包
作用是解析bean对象,使其转换为符合json格式的字符串,可以通过jackson关键字在aliyun的maven仓库找到这三个jar包
<dependency >
<groupId > com.fasterxml.jackson.core</groupId >
<artifactId > jackson-databind</artifactId >
<version > 2.9.6</version >
</dependency >
<dependency >
<groupId > com.fasterxml.jackson.core</groupId >
<artifactId > jackson-core</artifactId >
<version > 2.9.6</version >
</dependency >
<dependency >
<groupId > com.fasterxml.jackson.core</groupId >
<artifactId > jackson-annotations</artifactId >
<version > 2.9.6</version >
</dependency >
还要导入一个spring-mvc的jar包
<dependency >
<groupId > org.springframework</groupId >
<artifactId > spring-webmvc</artifactId >
<version > 4.3.9.RELEASE</version >
</dependency >
2.编写jsp页面
<fieldset >
<legend style ="font-size: 50px;" > 二级联动菜单</legend >
<select id ="province" onchange ="getCity(this.value)" >
<option > 请选择...</option >
<option value ="1" > 山西</option >
<option value ="2" > 山东</option >
<option value ="3" > 河北</option >
</select >
<select id ="city" >
<option > 请选择...</option >
</select >
</fieldset >
3.编写js代码,首先导入jQuery,就不演示怎么导入了
function getCity (provinceCode) {
$.ajax({
url:"${pageContext.request.contextPath}/getCity.do" ,
data:"code=" +provinceCode,
type:"get" ,
dataType:"json" ,
success:function (obj) {
$("#city" ).html("<option>选择城市</option>" );
for (i=0 ;i<obj.data.length;i++){
var option = new Option(obj.data[i].cityName,obj.data[i].cityCode);
$("#city" ).append(option);
}
}
})
}
4.创建bean包,City类
public class City implements Serializable {
private static final long serialVersionUID = 7987395232363092063 L;
private Integer cityCode;
private String cityName;
......
}
5.在bean包下写一个装json数据的类,类名随便起
public class ResponseResult <T > implements Serializable {
private static final long serialVersionUID = -4394155310369805409 L;
private Integer state;
private String message;
private T data;
......
......
......
}
6.写控制器层
@RequestMapping("/showUpdate.do" )
public String showUpdate(){
return "update" ;
}
@RequestMapping("/getCity.do" )
@ResponseBody
public ResponseResult< List < City>> getCity(Integer code){
ResponseResult< List < City>> rr = new ResponseResult< List < City>> (1 ,"成功" );
List < City> list = new ArrayList< City> ();
if (code == 1 ){
list . add(new City(11 ,"运城" ));
list . add(new City(12 ,"太原" ));
list . add(new City(13 ,"临汾" ));
... ...
}else if (code == 2 ){
list . add(new City(21 ,"潍坊" ));
list . add(new City(22 ,"菏泽" ));
... ...
}else {
list . add(new City(31 ,"秦皇岛" ));
list . add(new City(32 ,"廊坊" ));
list . add(new City(33 ,"石家庄" ));
... ...
}
rr. setData(list );
return rr;
}
至此这个用json实现的二级菜单联动的功能就实现了,由于我现在还是个学生,所以有的地方还不是很明白,而且还有一个BUG,就是当点击省份的‘选择省份’时,会报错,提示的是jQuery错,不知道是什么原因,如果有知道原因的大佬,可以留言沟通一下。