springmvc接收ajax的json格式数据

时间:2022-10-16 20:30:04

1.jsp封装数据,示例中是list数组

var saveList = new Array();
$.each($("#hasList tr"), function(i, n){
var a = $(n).find("td:first a"),
id = $(a).attr("data-id"),
name = $(a).text();
saveList.push({id:id,name:name});
});

2.ajax提交请求
$.ajax({
type: "POST",
url: "<%=basePath %>manage/setSchoolList",
contentType: 'application/json;charset=utf-8', //设置请求头信息
data: $.toJSON(saveList),
async: false,
success: function(data){
alert("设置成功");
}
});

3.springmvc接收数据

@ResponseBody
@RequestMapping(value = "/setSchoolList", method = {RequestMethod.POST})
public String setSchoolList(@RequestBody List<Map<String, Object>> list) {
String date = DateTool.getCurrenttime();
List<School> schoolList = new ArrayList<School>();
int count = 1;
for (Map<String, Object> map : list) {
School school = new School();
for (String key : map.keySet()) {
String value = (String) map.get(key);
if ("id".equals(key)) {
school = JsonpUtil.getSchoolBySchoolId(value);
}
}
school.setCreateTime(date);
school.setOrderNum(count++);
schoolList.add(school);
}
schoolService.insert(schoolList);

return "success";
}