Thymeleaf: Refresh value with Ajax

﹥>﹥吖頭↗ 提交于 2020-06-10 04:22:36

问题


I have this piece of code in a Thymeleaf template.

 <div class="alert_counter" th:classappend="${numDeviceEventsWithAlarm>0} ?  show_info">
                                    <span th:text="${numDeviceEventsWithAlarm}">${numDeviceEventsWithAlarm}</span>
                                </div>

Is it possible to refresh the value numDeviceEventsWithAlarm using Ajax and without F5 ??


回答1:


You can use the feature to only render a fragment of the Thymeleaf view.

First give the snippet of markup you want to update an id:

<span id="eventCount" th:text="${numDeviceEventsWithAlarm}"></span>

Then we can create a Spring request mapping in controller:

@RequestMapping(value="/event-count", method=RequestMethod.GET)
public String getEventCount(ModelMap map) {
    // TODO: retrieve the new value here so you can add it to model map
    map.addAttribute("numDeviceEventsWithAlarm", count);

    // change "myview" to the name of your view 
    return "myview :: #eventCount";
}

See Specifying fragments in controller return values in Thymeleaf manual to better understand the return that specifies which fragment to render.

Make a JavaScript function to update the value with ajax (jQuery style):

function updateEventCount() {
    $.get("event-count", function(fragment) { // get from controller
        $("#eventCount").replaceWith(fragment); // update snippet of page
    });
}

Then just call this function when you need to update the value.



来源:https://stackoverflow.com/questions/48891551/thymeleaf-refresh-value-with-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!