一、Json对象+@RequestBody接收
var val = {id: 1, name: "小明"};
$.ajax({
url: "/getJson",
dataType: "JSON",
type: "post",
contentType: 'application/json;charset=UTF-8',
data: JSON.stringify(val),
success: function (msg) {
console.log(msg)
}
})
后端获取参数:Map<String,Object>
@PostMapping("/getJson")
@ResponseBody
public Map getJsonVal(@RequestBody Map user) {
System.out.println("user = "+ user.get("id"));
System.out.println("user = "+ user.get("name"));
returnuser;
}
后端获取参数:对象
@PostMapping("/getJson")
@ResponseBody
public User getJsonVal(@RequestBody User user) {
returnuser;
}
二、传JSON对象#
var val = {"id": 1,"name":"小明"};
$.ajax({
url:"/getJson",
dataType:"JSON",
type:"post",
// contentType:'application/json;charset=UTF-8', //不能加
data: val,
success:function(msg) {
console.log(msg)
}
})
后端获取参数
@PostMapping("/getJson")
@ResponseBody
public User getJsonVal(@RequestParam("id") String id,@RequestParam("name") String name) {
User user = new User();
user.setId(Integer.parseInt(id));
user.setName(name);
returnuser;
}
三、json集合+@RequestBody接收#
var val = [{"id": 1,"name":"小明"},{"id": 2,"name":"小红"}];
$.ajax({
url:"/getJson",
dataType:"JSON",
type:"post",
contentType:'application/json;charset=UTF-8', //不能加
data: JSON.stringify(val),
success:function(msg) {
console.log(msg)
}
})
后端获取参数
@PostMapping("/getJson")
@ResponseBody
public List getJsonVal(@RequestBody List user) throws IOException {
for(User user2 : user){
System.out.println("user2 = "+ user2);
}
returnuser;
}
网友评论