2017-09-15 80 views
0

我试图使用与阿贾克斯Thymeleaf片段在我的项目,我有我的控制器上此方法: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) { 
    ^

上的HTML,我想通过AJAX添加的片段我这只是用于测试:

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

发生了什么是我得到“嘉宾的方法!”消息在控制台上,这意味着它到达的控制器,但它会尝试时要做到:

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

我得到一个NullPointerException,因为模型参数来了空。 所以我试着评论这一行,只是返回我想要显示的片段。 这是我的片段:我试图把$ {}内容文字注释的model.addAttribute线时硬编码

<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> 

,但我不会在我的屏幕上得到任何东西。

我需要做些什么来解决我所得到的“警告”,以及能够看到正确位置上显示的片段?

回答

0

我能够解决这样说:

不是使用此方法的:

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 。如果你需要在屏幕上使用任何东西,你可以添加Object来添加它的属性。

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

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

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