【问题标题】:Spring boot, Thymeleaf, Ajax, get null object from ajaxSpring boot,Thymeleaf,Ajax,从ajax获取空对象
【发布时间】:2021-08-01 08:19:06
【问题描述】:

我想在 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()) 我什么也没得到

【问题讨论】:

  • 您好,您在哪里调用setStatistic 方法?您是否尝试过从调试控制台显式序列化表单?像这样$('#profileStats').serialize()?
  • @atish.s 我调用方法window.onload = setStatistic()。是的,我在问题的最后写了它。我什么也得不到
  • 我的意思是在页面加载后检查页面并在调试控制台中执行$('#profileStats').serialize() 以查看结果或错误。

标签: ajax spring thymeleaf


【解决方案1】:

如果您想通过 AJAX 调用使用 ModelAttributeModelAndView,则不应在您的 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(...)
}

使用 ProgressResponseProfileStatsRequestBody 2 个新类,映射到您要发送/接收的 JSON。

【讨论】:

    【解决方案2】:

    您可能希望在表单中包含一些字段,以便 Spring 可以映射到 ProfileStats 对象中的各个字段。请参阅此处的示例:https://spring.io/guides/gs/handling-form-submission/

    【讨论】:

    • 这不适合我,因为我不发送表格,而是保留一个每秒在后台更新的计数器。这就是ajax的思想
    猜你喜欢
    • 2019-07-22
    • 2020-10-19
    • 2017-09-12
    • 1970-01-01
    • 2016-11-12
    • 2018-06-15
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多