SpringMVC--AJAX支持

业务方法获取AJAX发送的请求参数

JSP页面

1
2
3
4
5
6
7
8
9
10
11
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery-3.3.1.js" type="text/javascript"></script>
<script src="js/j.js" type="text/javascript"></script>
</head>
<body>
<a href="ajaxTest.jsp" id="ajax">ajax</a>
</body>
</html>

前端jQuery代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(function () {
$("#ajax").click(function () {
$.ajax({
url: "http://localhost:8080/ajaxtest",
type: "post",
contentType: "application/json;charset=utf-8",
data: '[{"name": "ymt", "age": 18},{"name": "yyt", "age": 22}]',
success:
function (result) {
alert("传送成功")
}
});
return false;
});
});

Role类

1
2
3
4
5
public class Role {
private String name;
private Integer age;
//get和set 方法
}

Controller代码

1
2
3
4
5
6
7
@RequestMapping("/ajaxtest")

//将前端传来的name,age信息封装到Role类中
//@requestBody可以将请求体中的JSON字符串绑定到相应的bean上,也可以将其分别绑定到对应的字符串上
public void ajax(@RequestBody List<Role> role){
System.out.println(role);
}

最后后端显示[Role{name='ymt', age=18}, Role{name='yyt', age=22}] 成功接收JSON数据

AJAX获取服务器响应的结果

Controller代码

1
2
3
4
5
6
7
//将前端发送过来的数据再返回去
@ResponseBody
@RequestMapping("/ajaxtest")
public List<Role> ajax(@RequestBody List<Role> role){
System.out.println(role);
return role;
}

JSP页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$(function () {
$("#ajax").click(function () {
$.ajax({
url: "http://localhost:8080/ajaxtest",
type: "post",
contentType: "application/json;charset=utf-8",
data: '[{"name": "ymt", "age": 18},{"name": "yzt", "age": 22}]',
success:
function (result) {
//将结果迭代出来
$.each(result,function (index,value) {
alert(value.name+value.age);
});
};
});
});
});
赏个🍗吧
0%