本文介绍了Thymeleaf动态表单操作网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>

Springboot

Springboot

如何为表单中的 th:action 操作网址"构造表达式?网址取决于名称" 变量.

How to construct expression for th:action "action url" in form? Url depends on "name" variable.

我正在尝试这样,但没有用:

I'm trying like this, but it's not working:

<form method="get"
    th:action="@{'/' + {baseUrl}(baseUrl=${#strings.isEmpty(name) ? '' : 'user/find/'})}">

    <input type="text" th:value="${name}"/>
    <button type="submit">Find</button>
    <button type="button"
            th:classappend="${#strings.isEmpty(name)}?'hidden':''"
            onclick="clearSearch()">X</button>
</form>

我尝试了这个,但是也行不通:

and I tried this, doesn't work too:

<form th:with="baseUrl=(${#strings.isEmpty(name) ? '/' : '/user/find/'})"
      th:action="@{${baseUrl}}" method="get">

推荐答案

抱歉.我意识到Thymeleaf不能动态处理输入字段.

Oh sorry. I realized Thymeleaf is not for dynamically handling input field.

我只写了一个JS代码.

I just write a JS code.

$(document).ready(function () {
    var searchForm = $(this).find('#searchForm');
    searchForm.on('click', '#searchButton', function (event) {
      var form = $('#searchForm');
      var name = $('#searchInputName').val();
      var addUrl = (name === '') ? '/' : '/user/find/';
      form.attr('action', addUrl);
    });
});

此后,我意识到可以在控制器中更简单地实现它了:)

after that I realized I can realize it simpler in my controller :)

@GetMapping("/user/find/")
public String getNextPage(Model model, Pageable pageable,
@RequestParam(name = "name") String name) {

    if (name.isEmpty()) return "redirect:/";
....
}

这篇关于Thymeleaf动态表单操作网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 12:16