springmvc 前端 发ajax请求的几种方式

时间:2022-10-06 20:36:26

一.传json单值或对象

1.前端

 1 var data = {'id':id,'name':name};
2 $.ajax({
3 type:"POST",
4 url:"user/saveUser",
5 dataType:"json",
6 //contentType:"application/json", //不能添加这个头
7 data:data, //这里不能进行JSON.stringify,发送请求的数据在:form data
8 success:function(data){
9
10 }
11 });

2.后端

//看成单值
@RequestMapping(value = "save", method = {RequestMethod.POST }})
@ResponseBody
public void save(@RequestParam int id,String name) { //这里字段要跟前端一致,@RequsetParam 可以不加,默认调用的就是它

}
//看成对象
@RequestMapping(value = "save", method = {RequestMethod.POST }})
@ResponseBody
public void save(User user) { //前端字段跟对象属性一致
//自动转化成改对象
}

二.json对象转成字符串后传值

1.1、前端

$.ajax({ 
type:
"POST",
url:
"user/saveUser",
dataType:
"json",
contentType:
"application/json", //需添加这个头
data:JSON.stringify(data), //发送请求的数据在request payload
success:function(data){

}
});

1.2、后端

//看成对象
@RequestMapping(value = "save", method = {RequestMethod.POST }})
@ResponseBody
public void save(@RequestBody User user) { //需添加RequestBody注解
//自动转化成改对象
}

三.将对象JSON.stringify后,以第一种方式传递,可实现对象中存对象 {'userList':users,'key1':value1}

1.前台

var user = {'id':id,'name':name};
var jsonStrGoods = JSON.stringify({'gid':gid,...});
$.ajax({
type:
"POST",
url:
"user/saveUser",
dataType:
"json",
// contentType:"application/json", //不添加这个头
data:{'user':JSON.stringify(user),'goods':jsonStrGoods }, //发送请求的数据在request payload
success:function(data){

}
});

2.后台

//看成单值
@RequestMapping(value = "save", method = {RequestMethod.POST }})
@ResponseBody
public void save(@RequestParam String user,String goods) { //这里字段要跟前端一致,@RequsetParam 可以不加,默认调用的就是它
User u= JSON.parseObject(user, User .class);//alibaba.fastjson转换成对象
}
//看成对象
@RequestMapping(value = "save", method = {RequestMethod.POST }})
@ResponseBody
public void save(UserAndGoods ug) { //没试过,猜测应该是这样,前端字段跟对象属性一致
//自动转化成改对象
}

传数组

前台

 

var arr = str.split(',');
$.ajax({
url:
'/appollo-console/manage/user/names/validation',
data:{
names:arr
},
traditional:
true,//必须
type:
'post',
dataType:
'json',
success:
function(res){
alert(res);
}
})

 

后台

@PostMapping("/names/validation")
@ResponseBody
public List<String> validateUserName(String[] names){
List<String> notValidNames = Lists.newArrayList();
notValidNames = userService.findNotValidNames(Arrays.asList(names));
return notValidNames;
}

 

 

 

总结:1.如果用JSON.stringify()将对象转成字符串,就需要在ajax请求中指定contentType 为 application/json,且后台需添加 @RequestBody注解;

   2.如果直接传json对象则跟上面的相反,不能指定contentType为 application/json,其默认类型是 application/x-www-form-urlencoded