Thymeleaf:使用Ajax刷新值 [英] Thymeleaf: Refresh value with Ajax

查看:2137
本文介绍了Thymeleaf:使用Ajax刷新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Thymeleaf模板中有这段代码.

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>

是否可以使用Ajax且不使用F5刷新值numDeviceEventsWithAlarm?

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

推荐答案

您可以使用该功能仅呈现Thymeleaf视图的片段.

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

首先提供要更新 id 的标记片段:

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

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

然后我们可以在控制器中创建一个Spring请求映射:

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";
}

请参见在Thymeleaf手册中的控制器返回值,以更好地了解指定要渲染的片段的返回.

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

使JavaScript函数使用 ajax(jQuery样式)来更新值:

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.

这篇关于Thymeleaf:使用Ajax刷新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆