首页 > 解决方案 > 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()) 我什么也没得到

标签: ajaxspringthymeleaf

解决方案


如果您想从 AJAX 调用中使用它,则不应在您的方法中使用ModelAttributeand 。ModelAndViewGetMapping

使用 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 个新类映射ProgressResponseProfileStatsRequestBody您要发送/接收的 JSON。


推荐阅读