前后端请求参数方式总结
1.简单参数
前端:
const base_url = 'http://localhost:8090'
const p1={
id: 12335464456,
name:'shiro'
}
// 简单参数
function send1() {
// get请求
$.ajax({
url: base_url + '/get/param',
data: p1,
type: 'get',
success: function (res) {
console.log("$$get1" + res);
}
})
}
function send2() {
// post请求
$.ajax({
url: base_url + '/post/param',
data: p1,
type: 'post',
success: function (res) {
console.log("$$post1" + res);
}
})
}
后端:
// 简单参数
// get请求
@GetMapping("/get/param")
public String getParam(@RequestParam("id") Long id,
@RequestParam("name") String name) {
log.info("简单参数get->{},{}",id,name);
return id + name;
}
// post请求
@PostMapping("/post/param")
public String postParam(@RequestParam("id") Long id,
@RequestParam("name") String name) {
log.info("简单参数post->{},{}",id,name);
return id + name;
}
请求详情:
-
get请求:是将参数拼接在url后面的方式
-
post请求:是将参数放在表单数据中提交
2.路径传参
前端:
const p2 = 1001
// 路径传参
function send3() {
// get请求
$.ajax({
url: base_url + '/get/param/' + p2,
type: 'get',
success: function (res) {
console.log("$$get2" + res);
}
})
}
后端:
// 路径传参
// get请求
@GetMapping("/get/param/{age}")
public String getPathVal(@PathVariable("age")Integer age) {
log.info("路径传参get->{}",age.toString());
return age.toString();
}
请求详情:
3.列表参数
前端:
// 列表参数
function send5() {
// post请求
$.ajax({
url: base_url + '/post/list',
type: 'post',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(lst),
success: function (res) {
console.log("$$post3" + res);
}
})
}
后端:
// 列表参数
// post请求
@PostMapping("/post/list")
public String postList(@RequestBody List<String> idList) {
log.info(idList.toString());
return idList.toString();
}
请求详情:
4.对象参数
前端:
const obj = {
username: 'shiro',
password: '123456',
nickName: 'zzzz',
hobbyList: [1, 2, 3],
gradeList: [
{ name: 'shiro', code: '1111' },
{ name: 'ziv', code: '2222' }
]
}
// 对象参数
function send7() {
// post请求
$.ajax({
url: base_url + '/post/object',
data: JSON.stringify(obj),
dataType: 'json',
type: 'post',
contentType: 'application/json',
success: function (res) {
console.log("$$$$$" + res);
}
})
}
后端:
// 对象参数
// post请求
@PostMapping("/post/object")
public String postObject(@RequestBody SystemUser user) {
log.info("路径传参post->{}",user.toString());
return JSON.toJSONString(user);
}
public class SystemUser extends BaseEntity{
private String username;
private String password;
private String nickName;
private List<String> hobbyList;
private List<Grade> gradeList;
}
public class Grade {
private String name;
private String code;
}
请求详情: