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

Thymeleaf中th:href如何获取select组件值作为URL请求参数

问题根因

你使用的th:href是Thymeleaf模板引擎的服务端渲染语法,会在服务端生成页面时就完成解析,输出固定的静态href值。你写入的JavaScript代码会被直接识别为普通字符串拼接进URL参数,不会在用户浏览器端执行获取select组件的实际选中值,因此服务端收到的就是这段JS代码原文。

修复方案

有两种常用的实现方式,都需要在客户端侧处理动态参数拼接:

方案1:点击时动态拼接参数跳转

先给a标签设置固定的基础路径,绑定点击事件处理动态参数:

<td class="body-item mbr-fonts-style display-7">
  <a id="exportBtn" th:href="@{/export(exportEntity='Person')}">Download</a>
</td>

添加对应的JS逻辑:

document.getElementById('exportBtn').addEventListener('click', function(e) {
  // 阻止默认跳转行为
  e.preventDefault();
  // 获取下拉框选中值
  const semesterValue = document.getElementById('semester').value;
  // 拼接参数后跳转
  window.location.href = `${this.href}&semester=${encodeURIComponent(semesterValue)}`;
});

方案2:下拉框值变化时提前更新链接

如果需要提前更新href属性,可监听select的change事件:

const exportBtn = document.getElementById('exportBtn');
const semesterSelect = document.getElementById('semester');

// 下拉框值变化时更新导出链接
semesterSelect.addEventListener('change', function() {
  const basePath = exportBtn.href.split('?')[0];
  exportBtn.href = `${basePath}?exportEntity=Person&semester=${encodeURIComponent(this.value)}`;
});

// 页面初始化时先赋值一次默认选中值
semesterSelect.dispatchEvent(new Event('change'));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:36:03