首页 > 解决方案 > 使用 Thymaleaf 和数据库抛出异常的动态下拉菜单

问题描述

我正在尝试做一个动态下拉菜单。首先,我必须从菜单中选择一个 IDE,然后根据我的选择,这个 IDE 的版本应该会出现。

1.第一个下拉菜单

<select class="field-title" id="ide1" name="ide1" th:field="*{ide}"  >
                <option th:each="ideSelected : ${ides}"
                        th:value="${ideSelected.getIDEName()}"
                        th:text="${ideSelected.getIDEName()}"></option>
            </select>
  1. 第二个下拉菜单
<select class="field-title" id="versionContent" name="versionContent" th:field="*{versions}" >          </select>
  1. 脚本
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#ide1").change(function() {
                sendAjaxRequest();
            });
        });
    </script>
    <script>
        function sendAjaxRequest() {
            let ide = $("#ide1").val();
            $.get("/ides/" + ide, function( data ) {
                // $("#versionContent").empty();
                data.forEach(function(item) {
                    let option = "<option value = " + item + ">" + item +  "</option>";
                    $("#versionContent").append(option);
                });
            });
        }
    </script>

  1. 控制器
@GetMapping(value = "/{ideName}")
    public Set<String> getAllVersions(@PathVariable("ideName") String ideName){
        IDE ide = ideService.getIdeByName(ideName);
        return ide.getVersions().stream().map(Version::getVersion).collect(Collectors.toSet());
    }
  1. 抛出错误
[THYMELEAF][http-nio-8080-exec-2] Exception processing template "ides/IntelliJ": An error happened during template parsing (template: "class path resource [templates/ides/IntelliJ.html]")

org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/ides/IntelliJ.html]")

有人可以帮我解决这个问题吗?谢谢!

标签: jqueryajaxspringdrop-down-menuthymeleaf

解决方案


要让 Spring 将控制器方法的响应序列化为 JSON,您需要使用@RestController,或者@ResponseBody在方法本身上使用@Controller.


推荐阅读