Spring MVC与jQuery AJAX处理响应数据详解
掌握Spring框架中@ResponseBody注解的使用方式,理解MVC架构中参数绑定与响应处理机制
jQuery AJAX方法success回调处理四种数据类型场景
1. 基础数据类型返回
前端直接获取响应数据
function fetchData() {
$.ajax({
url: '/api/student/create',
method: 'POST',
dataType: 'json',
success: function(response) {
console.log("基础数据:", response);
},
error: function() {
alert('请求失败');
}
});
}
后端控制器配置
@RestController
@RequestMapping("/student")
public class StudentController {
@PostMapping("/create")
public int createStudent() {
return 85;
}
}
2. 实体对象返回
前端解析JSON对象
function fetchData() {
$.ajax({
url: '/api/student/create',
method: 'POST',
dataType: 'json',
success: function(response) {
console.log("姓名:", response.name);
console.log("年龄:", response.age);
},
error: function() {
alert('请求失败');
}
});
}
后端实体类定义
public class User {
private String name;
private int age;
// Getter/Setter
}
3. 集合类型返回
前端遍历数组数据
function fetchData() {
$.ajax({
url: '/api/student/list',
method: 'POST',
dataType: 'json',
success: function(response) {
response.forEach((item, index) => {
console.log(`第${index}项:`, item);
for (let key in item) {
console.log(key, item[key]);
}
});
},
error: function() {
alert('请求失败');
}
});
}
后端集合返回实现
@RestController
@RequestMapping("/student")
public class StudentController {
@PostMapping("/list")
public List<User> getStudentList() {
List<User> userList = new ArrayList<>();
userList.add(new User("张三", 25));
userList.add(new User("李四", 30));
return userList;
}
}
4. 嵌套集合返回
前端处理多维数据结构
function fetchData() {
$.ajax({
url: '/api/student/nested',
method: 'POST',
dataType: 'json',
success: function(response) {
response.forEach((student, index) => {
console.log(`学生${index}:`);
for (let key in student) {
if (key === 'scores') {
student.scores.forEach((score, idx) => {
console.log(`分数${idx}:`, score);
});
} else {
console.log(key, student[key]);
}
}
});
},
error: function() {
alert('请求失败');
}
});
}
后端复杂对象构建
@RestController
@RequestMapping("/student")
public class StudentController {
@PostMapping("/nested")
public List<User> getNestedData() {
List<User> userList = new ArrayList<>();
userList.add(new User("王五", 22, Arrays.asList(90, 85)));
userList.add(new User("赵六", 28, Arrays.asList(88, 92)));
return userList;
}
}
