我有一个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";
}
和a。包含刷新片段的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
这似乎很有效,但刷新的事情让我害怕。。。如何根据添加到数据库的条目刷新页面?