Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  137] [ 6]  / answers: 1 / hits: 20943  / 6 Years ago, tue, february 20, 2018, 12:00:00

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


More From » jquery

 Answers
10

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").done(function(fragment) { // get from controller
$("#eventCount").replaceWith(fragment); // update snippet of page
});
}

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


[#55102] Friday, February 16, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zachary

Total Points: 175
Total Questions: 89
Total Answers: 108

Location: Fiji
Member since Wed, Jul 14, 2021
3 Years ago
;