我想在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发送到Controller:
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())时,我什么也得不到
发布于 2021-05-11 14:08:39
如果希望在AJAX调用中使用ModelAttribute和ModelAndView,则不应该在GetMapping方法中使用它们。
使用@RequestBody并返回@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(...)
}使用ProgressResponse和JSON 2个新类,它们映射到您想要发送/接收的ProfileStatsRequestBody。
发布于 2021-05-11 07:41:08
您可能希望在表单中包含一些字段,这样Spring就可以映射到ProfileStats对象中的各个字段。请参阅此处的示例:https://spring.io/guides/gs/handling-form-submission/
https://stackoverflow.com/questions/67478733
复制相似问题