ajax - Spring boot,Thymeleaf,Ajax,从ajax获取空对象
问题描述
我想立即在 ajax 中从表单中获取一个对象。对象有名称的地方,布尔值。但是在转移之后,由于某种原因,在 Controller 中它带有空字段。
这里的HTML代码:
<form id="profileStats" name="profileStats" action="#" th:action="@{/profile/{id}}" th:object="${profileStats}"
method="get">
<div class="photo">
<img src="./static/img/icon.ico" th:src="*{photoPath}" width="200px" height="200px"/>
</div>
<div class="info">
</div>
</form>
控制器,我将对象发送到 HTML:
@GetMapping("/{id}")
public String getProfile(@PathVariable("id") long id, Model model) {
ProfileStats stats = new ProfileStats(userClient.getClient());
model.addAttribute("profileStats", stats);
return "profile";
}
Ajax,我将对象从 HTML 发送到控制器:
function setStatistic() {
var $form = $('#profileStats');
$.ajax({
url: window.location.pathname + '/progress',
method: 'GET',
cache: false,
data: $form.serialize(),
success: function (data) {
$('.info').html(data);
if (data.search("done") >= 0) {
stopProgress();
}
},
error: function (e) {
console.log("error", e)
}
});
}
控制器,我从 AJAX 获取对象:
@GetMapping("/{id}/progress")
public ModelAndView getProgress(@ModelAttribute("profileStats") ProfileStats stats) {
ModelAndView modelAndView;
if (stats.isHaveAllMessage()) {
// HERE I GET NULL EXCEPTION
}
return modelAndView;
}
我究竟做错了什么?
在调试 console.log($form.serialize()) 我什么也没得到
解决方案
如果您想从 AJAX 调用中使用它,则不应在您的方法中使用ModelAttribute
and 。ModelAndView
GetMapping
使用 a@RequestBody
并返回 a @ResponseBody
。在您的 AJAX 调用中,从要发送和接收的表单数据创建 JSON。
@ResponseBody
@GetMapping("/{id}/progress")
public ProgressResponse getProgress(@PathVariable("id) String id, @RequestBody ProfileStatsRequestBody requestBody) {
//.. do whatever needs to be done here
return new ProgressResponse(...)
}
和2 个新类映射ProgressResponse
到ProfileStatsRequestBody
您要发送/接收的 JSON。
推荐阅读
- r - 使用 rstatix 运行单向重复测量 anova 但无法正常工作
- clion - 如何清除CLion中变量的附加颜色
- javascript - 在 React Native 中将参数向下传递四级
- typescript - 打字稿确保类型包含子字符串
- typescript - Vue.js 元素 UI 表单验证时使用 ts 验证为两个函数
- amazon-web-services - AWS Cloudformation - 它是可变的还是不可变的基础设施?
- javascript - 使用 CSS map 方法并排对齐 React JS 中的图像
- ruby-on-rails - SyntaxError:无效的正则表达式
- c++ - 在 C++20 中声明具有依赖类型参数的模板函数
- php - 如何获取特定数组项的计数