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

SpringBoot+Thymeleaf获取下拉框值触发表单提交遇错误求助

问题排查与解决方案

错误原因分析

  • 拼写错误导致未定义函数:代码中alret(form.action)是笔误,正确写法为alert(form.action),浏览器会因识别到未定义的alret抛出ReferenceError。
  • 第二个下拉框缺少name属性:blogCategory下拉框仅设置了th:id,未添加name="blogCategory"属性,导致document.querySelector('select[name="blogCategory"]')无法找到目标元素,调用.value时会抛出Cannot read properties of null的错误。

修正后的完整代码

<script>
    function updateAction() {
        var form = document.getElementById('myForm');
        var langSelect = document.querySelector('select[name="langCode"]');
        var categorySelect = document.querySelector('select[name="blogCategory"]');

        var currentUrl = new URL(window.location.href);
        currentUrl.searchParams.set('langCode', langSelect.value);
        currentUrl.searchParams.set('blogCategory', categorySelect.value);

        form.action = currentUrl.toString();
        alert(form.action);
        form.submit();
    }
</script>

<form id="myForm" th:action="@{/blogs}" method="post" th:with="language=${#locale.language}">
    <select name="langCode" onchange="updateAction()">
        <option th:value="es" th:selected="${language=='es'}">Español</option>
        <option th:value="fr" th:selected="${language=='fr'}">Français</option>
        <option th:value="pt" th:selected="${language=='pt'}">Português</option>
        <option th:value="en" th:selected="${language=='en'}">English</option>
    </select>

    <select name="blogCategory" th:id="blogCategory" onchange="updateAction()">
        <option value="value1">Option 1</option>
        <option value="value2">Option 2</option>
        <option value="value3">Option 3</option>
    </select>
</form>

额外优化建议

如果使用POST方法,更规范的做法是无需修改action的URL,直接通过表单字段传递参数:

  • 删除JavaScript中修改URL的逻辑,保持表单action为@{/blogs}
  • 确保两个下拉框都存在name属性,表单提交时会自动将选中值作为POST参数发送到后端

内容的提问来源于stack exchange,提问作者Nunyet Calçada

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 14:46:19