【问题标题】:Dynamic Drop down menu using Thymealeaf and database throw exception使用 Thymaleaf 和数据库抛出异常的动态下拉菜单
【发布时间】:2020-09-23 08:22:46
【问题描述】:

我正在尝试做一个动态下拉菜单。首先,我必须从菜单中选择一个 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]")

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

【问题讨论】:

  • 您的控制器是@Controller 还是@RestController?如果你想从你的控制器返回 JSON,你需要有一个 @RestController,或者如果你使用的是 @Controller,则只用 @ResponseBody 注释那个单一的方法。
  • 是的,我将其更改为 @RestController 并且有效!谢谢!
  • 添加了我的评论作为答案,以便您接受答案。

标签: jquery ajax spring drop-down-menu thymeleaf


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    • 2013-02-15
    • 2013-11-05
    相关资源
    最近更新 更多