我有一个Spring Web应用程序,其中每10秒向数据库添加一些条目。当新条目添加到数据库时,我希望我的页面自动重新加载。到目前为止,我已经提出了这样的代码:
function contentRefresh() {
$.ajax({
url: "/refresh",
success: function(data) {
console.log(data);
$("#main-content").html(data);
}
});
}
从控制器返回的数据是一个html片段:
@RequestMapping("/refresh")
public String refreshPage(Model model, Pageable pageable){
PageWrapper<NetworkHashrate> page = new PageWrapper<NetworkHashrate>(netService.getAllNetworks(pageable), "");
model.addAttribute("page", page);
model.addAttribute("networkHashrates", page.getContent());
return "main :: table-content";
}
包含刷新片段的.html:
<div class="table-responsive" id="main-content" th:fragment="table-content">
<table class="table table-hover ">
<thead class="thead-inverse">
<tr>
<th class="col-md-2 text-center">Network Id</th>
<th class="col-md-2 text-center">Rep_date</th>
<th class="col-md-2 text-center">Hashrate</th>
</tr>
</thead>
<tr style="cursor: pointer;" th:each="networkHashrate : ${networkHashrates}" th:onclick="'javascript:openPoolModal(\''+ ${networkHashrate.id} + '\');'">
<td class="text-center" th:text="${networkHashrate.id}"> Sample id</td>
<td class="text-center" th:text="${networkHashrate.rep_date}">Sample rep-date</td>
<td class="text-center" th:text="${networkHashrate.hashrate}">Sample hashrate</td>
</td>
</tr>
</table>
<button type="button" class="btn btn-success" th:onclick="'javascript:contentRefresh();'">Refresh!</button>
<div class="text-center" id="stat">
<div class="pagination"><p>Displaying <span class="badge" th:text="${page.size * (page.number-1) + 1}"></span> -
<span class="badge" th:text="${page.lastPage ? page.totalElements : page.size * (page.number-1)+ page.size}"></span> of
<span class="badge" th:text="${page.totalElements}"></span> total records</p>
</div>
</div>
</div>
早些时候,我一直在通过<meta http-equiv="refresh" content="60" />
刷新页面......但我被告知这是一个糟糕的方法。我已经使用button
测试了JS代码并且它似乎有效,但刷新事情让我害怕...如何根据数据库中的条目添加来刷新页面?
答案 0 :(得分:0)
我在我的JS脚本中添加了setInterval
,如:
setInterval("contentRefresh();", 10000 );
不是硬刷新,而是重新加载内容的Ajax调用,所以我想这样可行。