【问题标题】:Thymeleaf with Ajax not working properlyThymeleaf 与 Ajax 无法正常工作
【发布时间】:2018-02-24 20:58:16
【问题描述】:

我正在尝试在我的项目中使用带有 Ajax 的 Thymeleaf 片段,并且我的控制器上有这个方法:

public def displayInfo(Model model) {
    log.info("Guests method!")
    model.addAttribute("content", "testing ajax");
    "fragments/content::form-basic";
}

我在运行应用程序之前收到此消息:

WARNING: The [displayInfo] action in [ca.capilanou.hrpay.workload.NonInstructionalWorkloadController] accepts a parameter of type [org.springframework.ui.Model].  Interface types and abstract class types are not supported as command objects.  This parameter will be ignored.

    public def displayInfo(Model model) {
    ^

在我想通过 ajax 添加片段的 html 上,我有这个只是为了测试:

<button id="bt1" onclick="$('#content').load('/nonInstructionalWorkload/displayInfo');">Load Frag 1</button>
<div id="content"></div>

发生的事情是我得到了“Guests 方法!”控制台上的消息,这意味着它正在到达控制器,但是当它尝试这样做时:

model.addAttribute("content", "testing ajax");

我得到一个 nullPointerException,因为模型参数即将为空。 所以我尝试评论这一行并返回我想要显示的片段。 这是我的片段:

<th:block th:fragment="content" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <div th:text="${content}"></div>
</th:block>

在评论 model.addAttribute 行时,我尝试将 ${content} 文本硬编码,但屏幕上没有返回任何内容。

我需要做些什么来修复我收到的“警告”以及能够看到片段显示在正确的位置?

【问题讨论】:

    标签: java ajax spring spring-boot thymeleaf


    【解决方案1】:

    我可以这样解决:

    不要使用这种方法:

    public def displayInfo(Model model) {
        log.info("Guests method!")
        model.addAttribute("content", "testing ajax");
        "fragments/content::form-basic";
    }
    

    我现在正在使用这个:

    ModelAndView addWorkItem() {
            log.info("Display Fragment using Ajax")
            ModelAndView modelAndView = new ModelAndView("/fragments/content :: content")
            modelAndView.addObject("content", "Hello World!")
            return modelAndView
        }
    

    我们需要返回 ModelAndView。如果您需要在屏幕上使用任何东西,您可以 addObject 添加其属性。

    通过这样做,我避免了模型,因此我摆脱了警告问题。

    就是这样。我无法在任何地方找到这个解决方案。我在不同的文章中找到了片段。

    https://github.com/dandelion/dandelion/issues/28

    http://www.marcelustrojahn.com/2016/08/spring-boot-thymeleaf-fragments-via-ajax/

    http://www.xpadro.com/2014/02/thymeleaf-integration-with-spring-part-2.html

    【讨论】:

      猜你喜欢
      • 2017-08-13
      • 1970-01-01
      • 2022-01-22
      • 2013-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-11
      相关资源
      最近更新 更多