2017-09-15 31 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