You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Thymeleaf、Java与Spring MVC更新HTML数据表格的实现方案咨询

实现方案

第一步:后端新增JSON数据接口

在你的控制器类中新增一个接口,专门返回所有评分的JSON数据,无需渲染页面:

@GetMapping("/api/scores")
@ResponseBody
public Iterable<SimplePoker> getAllScores() {
    return simplePokerRepository.findAll();
}

如果你的控制器类用了@RestController注解可以不用加@ResponseBody,普通@Controller类加上该注解后,Spring会自动将返回的对象序列化为JSON格式。

第二步:前端修改

  1. 先给现有表格的tbody标签加唯一ID,方便后续操作DOM:
<tbody id="scoreTableBody">
    <tr th:each="score: ${scores}">
        <td th:text="${score.name}"></td>
        <td th:text="${score.planningScore}"></td>
        <td th:text="${score.risk1Score}"></td>
        <td th:text="${score.risk2Score}"></td>
        <td th:text="${score.risk3Score}"></td>
    </tr>
</tbody>
  1. 在表格下方的目标区域添加更新按钮:
<div class="text-center mt-3 mb-3">
    <button id="refreshBtn" class="btn btn-warning">更新表格</button>
</div>
  1. 页面底部添加JS代码实现刷新逻辑,这里提供两种实现方式可选:
基于jQuery实现(Bootstrap项目通常默认引入jQuery,推荐使用)
<script>
// 封装刷新表格的公共方法
function refreshScoreTable() {
    $.get("/api/scores", function(data) {
        // 清空原有表格内容
        $("#scoreTableBody").empty();
        // 遍历最新数据拼接表格行
        data.forEach(function(score) {
            var row = `<tr>
                <td>${score.name}</td>
                <td>${score.planningScore}</td>
                <td>${score.risk1Score}</td>
                <td>${score.risk2Score}</td>
                <td>${score.risk3Score}</td>
            </tr>`;
            $("#scoreTableBody").append(row);
        });
    });
}

// 绑定按钮点击事件
$("#refreshBtn").click(function() {
    refreshScoreTable();
});

// 可选:开启自动刷新,每3秒拉取一次数据,时间可自行调整,单位为毫秒
setInterval(refreshScoreTable, 3000);
</script>
原生JS实现(无需引入任何额外依赖)
<script>
function refreshScoreTable() {
    fetch("/api/scores")
        .then(response => response.json())
        .then(data => {
            const tbody = document.getElementById("scoreTableBody");
            tbody.innerHTML = '';
            data.forEach(score => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${score.name}</td>
                    <td>${score.planningScore}</td>
                    <td>${score.risk1Score}</td>
                    <td>${score.risk2Score}</td>
                    <td>${score.risk3Score}</td>
                `;
                tbody.appendChild(row);
            });
        });
}

document.getElementById("refreshBtn").addEventListener('click', refreshScoreTable);

// 可选:开启自动刷新
setInterval(refreshScoreTable, 3000);
</script>

内容的提问来源于stack exchange,提问作者Jon H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 22:36:04