如何传递JSON数据到后台?
方式一, 使用post请求,请求类型为:application/x-www-form-urlencoded; charset=UTF-8
$.ajax({
url : url,
type : 'POST',
data : {
username : $("input[name='username']").val(),
userCode : $("input[name='userCode']").val(),
tureName : $("input[name='tureName']").val(),
password : hex_md5(password),
deptId : $("input[name='deptId']").val(),
roleId : $("input[name='roleId']").val()
},
contentType : "application/x-www-form-urlencoded; charset=UTF-8",
dataType : 'json',
success : function(result) {
//...
}
});
http请求体如下:
可以看出, json对象的数据,被转化为表单请求数据传递到服务器上。
后台接收数据:
@ResponseBody
@RequestMapping(value = "/user/edit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON)
public String editUser(User user) {//...}
方式二,使用Post请求,请求数据类型为:application/json到后台,此方式可传递复杂的json数据对象到后台。
$.ajax({
url : url,
type : 'POST',
data : JSON.stringify({
username : $("input[name='username']").val(),
userCode : $("input[name='userCode']").val(),
tureName : $("input[name='tureName']").val(),
password : hex_md5(password),
deptId : $("input[name='deptId']").val(),
roleId : $("input[name='roleId']").val()
}),
contentType : 'application/json',
dataType : 'json',
success : function(result) {
//....
}
});
http请求体如下:
contentType : 'application/json;charset=utf-8' 表示前台传递数据为json类型数据,作为请求体内容提交到服务器,中文需要加上编码方式。
dataType : 'json', 表示前天希望后台响应的数据类型
其中 data数据需要用JSON.stringify来将JSON对象转化为JSON字符串。
后台@RequestBody来标识需要从请求体中解析数据,如下:
@ResponseBody
@RequestMapping(value = "/user/edit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON)
public String editUser(@RequestBody User user) {//...}