这是我的代码
//javaScript code
var sampleDataList= [];
var dataSample = {
name:"name",
id:"id"
};
sampleDataList.push(dataSample);
sampleDataList.push(dataSample);
$.ajax({
type : "POST",
url : "saveData",
data : sampleDataList,
//data:mydata,
contentType : "json",
async:false,
success : function(data) {
},error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
//TO class
public class DataSample {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
//Controller
@RequestMapping(value = "/saveData", method = RequestMethod.POST)
public void saveDatas(ArrayList<DataSample> dataSamp){
System.out.println(asdf);
}
我能够点击控制器,但dataSamp(saveDatas方法的参数)没有任何值。它被收到空列表。
请告知我的代码出了什么问题?或者请问我怎么做到这一点?
答案 0 :(得分:-1)
发送ajax-request时使用JSON.stringify():
$.ajax({
type : "POST",
url : "saveData",
data : JSON.stringify(sampleDataList),
//data:mydata,
...
如果我没有弄错,你还需要请求参数中的@RequestBody注释:
@RequestMapping(value = "/saveData", method = RequestMethod.POST)
public void saveDatas(@RequestBody ArrayList<DataSample> dataSamp){
System.out.println(asdf);
}
添加jackson依赖项以将json转换为object,反之亦然
<dependency><!-- jackson -->
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version></version>
</dependency>