首先确保Spring后端使用@RestController或@ResponseBody返回JSON,前端用fetch或$.ajax发送请求并解析响应,注意处理CORS跨域配置,调试时检查Network面板确认数据正确返回。

在前后端分离的开发模式中,前端使用 JavaScript 发送请求,后端通过 Spring 框架返回 JSON 数据是常见做法。要成功获取 Spring 返回的 JSON 数据,关键在于正确发送请求并处理响应。以下是具体操作方法。
Spring MVC 或 Spring Boot 中,控制器方法需使用 @ResponseBody 注解或直接使用 @RestController,以确保返回内容为 JSON 格式。
示例代码:@RestController
public class DataController {
@GetMapping("/api/user")
public User getUser() {
return new User("张三", 25);
}
}
上述接口访问时会自动将 User 对象序列化为 JSON 并返回。
现代浏览器推荐使用 fetch 发起请求。它基于 Promise,语法简洁,适合处理异步操作。
fetch('/api/user')
.then(response => {
if (!response.ok) {
throw new Error('网络请求失败');
}
return response.json(); // 将响应体解析为JSON
})
.then(data => {
console.log(data); // { name: "张三", age: 25 }
})
.catch(error => {
console.error('请求出错:', error);
});
注意:必须调用 response.json() 方法才能将原始响应转为 JavaScript 对象。
如果项目中使用了 jQuery,可以通过 $.ajax 获取数据。
$.ajax({
url: '/api/user',
type: 'GET',
dataType: 'json', // 声明期望返回的数据类型
success: function(data) {
console.log(data); // 自动解析后的JSON对象
},
error: function(xhr, status, error) {
console.error('请求失败:', error);
}
});
设置 dataType: 'json' 可让 jQuery 自动解析 JSON 字符串。
若前端与后端不在同一域名下,需在 Spring 端配置 CORS 支持,否则浏览器会阻止请求。
添加注解方式:@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/api/user")
public User getUser() {
return new User("张三", 25);
}
或全局配置:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:3000")
.allowedMethods("GET", "POST");
}
}
基本上就这些。只要后端正确输出 JSON,前端合理发起请求并解析响应,就能顺利获取数据。调试时可打开浏览器开发者工具查看 Network 面板,确认请求是否成功、返回格式是否正确。不复杂但容易忽略细节。
以上就是JS如何获取Spring返回的JSON数据_JS获取Spring返回JSON数据的操作指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号