前后端分离 - Ajax请求和Controller接收示例

本文最后更新于:2025年2月18日 下午

前后端分离 - Ajax请求和Controller接收示例

Maven依赖

1

后端准备

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// 统一返回类、

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
* 数据返回值实体类
* 此类主要用于响应前端的请求
*/
@Data
@ApiModel(value = "响应类")
public class R<T>{

/**
* 响应码 >>> 200成功
*/
@ApiModelProperty(value = "响应码",name = "code")
private int code;

/**
* 数据返回值 >>> 响应信息
*/
@ApiModelProperty(value = "响应信息",name = "message",position = 1)
private String message;

/**
* 数据返回值 >>> 响应数据
*/
@ApiModelProperty(value = "响应数据",name = "data",position = 2)
private T data;

/**
* 自定义响应信息【单例模式】
* @param data 响应数据
* @param code 响应代码枚举
* @param message 响应信息
* @return ResultData
*/
public static <T> R<T> BUILD(T data, int code,String message) {
R<T> result = new R<>();
result.setData(data);
result.setCode(code);
result.setMessage(message);
return result;
}

}

后端Controller

1
2
3
4
5
6
7
8
9
// 给登录页添加路径
@Controller
public class IndexController {

@GetMapping("demo")
public String demo() {
return "demo";
}
}

前端准备

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>前后端传值匹配Demo</title>
<!-- jquery -->
<script src="../static/dist/js/jquery.min.js"></script>
</head>
<body>
<form>
<label for="user-name-label">用户名:</label><br />
<input id="user-name-label" type="text" name="username" placeholder="请输入用户名"><br />
<label for="user-password-label">密码:</label><br />
<input id="user-password-label" type="password" name="password" placeholder="请输入密码"><br />
<button type="submit">登录</button>
</form>
<script>
// TODO: 这里写ajax异步请求
</script>
</body>
</html>

直接传参

后端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 这种方法需固定顺序[不推荐]
@PostMapping(value="/directExample")
@ResponseBody
public R<Map<String,Object>> directExample(String username,String password){

Map<String,Object> map = new HashMap<>();
map.put("username",username);
map.put("password",password);
System.out.println("username = " + username + ", password = " + password);

return R.BUILD(map,200,"请求成功");
}

// 这种无需固定顺序[推荐]
@PostMapping(value="/directExample2")
@ResponseBody
public String directExample2(
@RequestParam(value = "username")
String username,
@RequestParam(value = "password")
String password){

Map<String,Object> map = new HashMap<>();
map.put("username",username);
map.put("password",password);
System.out.println("username = " + username + ", password = " + password);

return R.BUILD(map,200,"请求成功");
}

前端js

依赖jquery-3.6.0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$('form').on('submit', function(event) {
event.preventDefault(); // 阻止默认提交行为
// 将表单数据序列化为对象
const formData = {
username: $('input[name="username"]').val(),
password: $('input[name="password"]').val(),
};
console.log(formData);
// 使用 AJAX 提交数据
$.ajax({
url: '/directExample2',
type: 'POST',
data: formData,
success: function(data) {
let code = data.code;
if (code===200) {
console.log(data);
} else {
console.log("登录失败!")
alert(data.message);
}
},
error: function(xhr, status, error) {
console.error('提交失败: ', error);
}
});
});

请求头传参

后端

Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@GetMapping(value="/requestHeaderExample")
@ResponseBody
public R<Map<String,Object>> requestHeaderExample(
@RequestHeader("token")
String token,
@RequestParam(value = "username")
String username,
@RequestParam(value = "password")
String password){
Map<String,Object> map = new HashMap<>();
map.put("token",token);
map.put("username",username);
map.put("password",password);
System.out.println("token = " + token + ",username = " + username + ", password = " + password);
return R.BUILD(map,200,"请求成功");
}

前端

js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
$('form').on('submit', function(event) {
event.preventDefault(); // 阻止默认提交行为
// 将表单数据序列化为对象
const formData = {
username: $('input[name="username"]').val(),
password: $('input[name="password"]').val(),
};
console.log(formData);
// 使用 AJAX 提交数据
$.ajax({
url: '/requestHeaderExample', // 替换为服务器的 URL
type: 'POST',
headers: {
'token': "12345"
},
data: formData, // 表单数据
success: function(data) {
let code = data.code;
if (code===200) {
console.log(data);
} else {
console.log("登录失败!")
alert(data.message);
}
},
error: function(xhr, status, error) {
console.error('提交失败: ', error);
}
});
});


Cookie传参

后端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@GetMapping(value="/cookieExample")
@ResponseBody
public R<Map<String,Object>> cookieExample(
@CookieValue("cookie")
String cookie,
@RequestParam(value = "username")
String username,
@RequestParam(value = "password")
String password){
Map<String,Object> map = new HashMap<>();
map.put("cookie",cookie);
map.put("username",username);
map.put("password",password);
System.out.println("token = " + token + ",username = " + username + ", password = " + password);
return R.BUILD(map,200,"请求成功");
}

前端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$('form').on('submit', function(event) {
event.preventDefault(); // 阻止默认提交行为
// 将表单数据序列化为对象
const formData = {
username: $('input[name="username"]').val(),
password: $('input[name="password"]').val(),
};
console.log(formData);
// 使用 AJAX 提交数据
$.ajax({
url: '/cookieExample', // 替换为服务器的 URL
type: 'POST',
xhrFields: {
withCredentials: true // 允许发送 Cookies
},
data: formData, // 表单数据
success: function(data) {
let code = data.code;
if (code===200) {
console.log(data);
} else {
console.log("登录失败!")
alert(data.message);
}
},
error: function(xhr, status, error) {
console.error('提交失败: ', error);
}
});
});

JSON传参

后端

DTO类,用于接收前端json数据的对象

1
2
3
4
5
6
7
8
9
10
11
import lombok.Data;

@Data
public class UserDTO {

// 用户名
private String username;
// 密码
private String password;
}

Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
@PostMapping(value="/JSONExample")
@ResponseBody
public ResultData<Map<String, Object>> JSONExample(
@RequestBody
UserDTO userDTO){

Map<String,Object> map = new HashMap<>();
map.put("username",userDTO.getUsername);
map.put("password",userDTO.getPassword);
System.out.println("username = " + username + ", password = " + password);

return ResultData.BUILD(map,200,"请求成功");
}

前端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$('form').on('submit', function(event) {
event.preventDefault(); // 阻止默认提交行为
// 将表单数据序列化为对象
const formData = {
username: $('input[name="username"]').val(),
password: $('input[name="password"]').val(),
};
console.log(formData);
// 使用 AJAX 提交数据
$.ajax({
url: '/JSONExample', // 替换为服务器的 URL
type: 'POST',
contentType: 'application/json', // 设置内容类型为 JSON
data: JSON.stringify(formData), // 转换为 JSON 字符串
success: function(data) {
let code = data.code;
if (code===200) {
console.log(data);
} else {
console.log("登录失败!")
alert(data.message);
}
},
error: function(xhr, status, error) {
console.error('提交失败: ', error);
}
});
});

路径传参

后端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@PostMapping(value="/PathExample/{id}")
@ResponseBody
public ResultData<Map<String, Object>> PathExample(
@PathVariable
String id,
@RequestParam(value = "username")
String username,
@RequestParam(value = "password")
String password){

Map<String,Object> map = new HashMap<>();
map.put("id",id);
map.put("username",username);
map.put("password",password);
System.out.println("username = " + username + ", password = " + password);

return ResultData.BUILD(map,200,"请求成功");
}

前端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$('form').on('submit', function(event) {
event.preventDefault(); // 阻止默认提交行为
// 将表单数据序列化为对象
const formData = {
username: $('input[name="username"]').val(),
password: $('input[name="password"]').val(),
};
console.log(formData);
// 使用 AJAX 提交数据
$.ajax({
url: '/PathExample/1', // 路径上直接加参数
type: 'POST',
contentType: 'application/json', // 设置内容类型为 JSON
data: JSON.stringify(formData), // 转换为 JSON 字符串
success: function(data) {
let code = data.code;
if (code===200) {
console.log(data);
} else {
console.log("登录失败!")
alert(data.message);
}
},
error: function(xhr, status, error) {
console.error('提交失败: ', error);
}
});
});

前后端分离 - Ajax请求和Controller接收示例
https://superlovelace.top/2024/10/19/前后端传值匹配/
作者
棱境
发布于
2024年10月19日
更新于
2025年2月18日
许可协议