json非同期の2級メニュー連動demoノート
1.まず3つのjarパッケージをインポートする
2.jspページの作成
3.jsコードを作成するには、まずjQueryをインポートし、どのようにインポートするかを説明しません.
4.beanパッケージ、Cityクラスの作成
5.beanパッケージの下にjsonデータを入れたクラスを書き、クラス名を勝手につける
6.ライトコントローラ層
bean , json , jackson aliyun maven jar
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.6version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.9.6version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.9.6version>
dependency>
spring-mvc jar
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.3.9.RELEASEversion>
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をインポートし、どのようにインポートするかを説明しません.
// jQuery
function getCity(provinceCode){
// ajax
$.ajax({
//
url:"${pageContext.request.contextPath}/getCity.do",
// , get url ? , , &
data:"code="+provinceCode,
//
type:"get",
//
dataType:"json",
//obj json
success:function(obj){
// , , ,
$("#city").html("");
// json
for(i=0;i// option , , ,
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 = 7987395232363092063L;
//
private Integer cityCode;
//
private String cityName;
// get set ( , , )
......
// tostring、hashcode、equals
// , ,
}
5.beanパッケージの下にjsonデータを入れたクラスを書き、クラス名を勝手につける
// json
//
public class ResponseResult<T> implements Serializable{
private static final long serialVersionUID = -4394155310369805409L;
//
private Integer state;
//
private String message;
//json
private T data;
// get set ( , )
......
// tostring、hashcode、equals
......
// , , ,
......
}
6.ライトコントローラ層
// updata
//
@RequestMapping("/showUpdate.do")
public String showUpdate(){
// jsp
return "update";
}
// city
@RequestMapping("/getCity.do")
// ,
@ResponseBody
// list ,
public ResponseResult<List<City>> getCity(Integer code){
// json
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," "));
......
}
// list json
rr.setData(list);
//
return rr;
}
json , , , BUG, ‘ ’ , , jQuery , , , 。