ajax请求
ajax请求主要有两种请求方式:1.get 2.post(delete,put)
get请求
get请求,请求参数由url携带,前端代码如下
$("#get请求").on("click",function () {
$.ajax({
type: "get",
url: "http://localhost:8080/shop/request/get?name=小念&name=小婷",
dataType: "json",
success: function (data) {
alert(data)
}
})
});
当请求参数放在 data 中时,data的值是一个json对象则会将参数拼接到url中,后端用 @RequestParam 注解接收,data 的值是一个json字符串时,后端用@RequestBody接收
$("#get请求").on("click",function () {
$.ajax({
type: "get",
url: "http://localhost:8080/shop/request/get",
dataType: "json",
data: {
name: "小婷"
},
success: function (data) {
alert(data)
}
})
});
get请求在后端由以下几种方试接收参数:1.单个参数接收 2.对象接收 3.map集合接收 4.request接收
//单个参数接收
//注意点:当一个参数是数组时,接收时以数组接收即可
//@GetMapping("/get")
public String getTest01(@RequestParam("name") String name){
System.out.println(name);
return name;
}
//以对象接收
//注意点:对象中的对象属性在前端传值是属性名: 对象属性.对象属性的属性
//@GetMapping("/get")
public String getTest02(Brand brand){
System.out.println(brand.getName());
return brand.getName();
}
//以map接收
//注意点:map接收需要添加注解@RequestParam
//@GetMapping("/get")
public String getTest03(@RequestParam Map map){
System.out.println(map.get("name"));
return (String)map.get("name");
}
//以HttpServletRequest接收
//这个相当于是原生Servlet
@GetMapping("/get")
public String getTest04(HttpServletRequest request){
System.out.println(request.getParameter("name"));
return request.getParameter("name");
}
post请求
post也可以在url中携带参数,接收方式和get方式一致,post请求以requestBody接收时,前端传入body的参数必须是一个json字符串,不能是json对象
$("#post请求").on("click",function () {
$.ajax({
type: "post",
url: "http://localhost:8080/shop/request/post",
//指定参数格式为json,不能少
contentType: "application/json",
dataType: "json",
//JSON.stringify() : 将json对象转为json字符串
data: JSON.stringify({
"name" : [
"小念","小婷"
],
"id" : "1"
}),
success: function (data) {
alert("成功");
alert(data)
},
error: function (data) {
alert("失败")
}
})
})
requestBody接收参数时,后端接收的是一个json字符串,只能整体接收,不能部分接收
//以requestBody
//这个注解接受的是一整个json字符串,不能单独接受某一个或某几个参数
//注意点:以requestBody接收前端需要传一个json字符串而不是json对象
//以对象接收
//@PostMapping("/post")
public Brand postTest01(@RequestBody Brand brand){
System.out.println(brand.getName());
return brand;
}
//以RequestParam接收, 这个注解只会接收url中携带的参数,不会接收body中的
//以字符串接收requestBody中的参数
//@PostMapping("/post")
public String postTest03(@RequestBody String name,@RequestParam("name") String age){
System.out.println(age);
System.out.println(name);
return name;
}
//以map接收
@PostMapping("/post")
public String postTest04(@RequestBody Map<String,Object> map){
System.out.println(map.size());
return map.size()+"";
}
delete请求和put请求同post请求一致
关于ContentType属性
这个属性的值是一个字符串,默认值是: application/x-www-form-urlencoded
这个值会把data中的数据变为key=value的形式,每组之间用&隔开,适用于get请求方式,application/json,这种方式时data中必须是一个json字符串