【问题标题】:create get method on onclick method在 onclick 方法上创建 get 方法
【发布时间】:2015-02-09 10:21:26
【问题描述】:

当有人使用 Thymeleaf 和 Spring 在“选择”中单击“选项”元素时,我想获取有关客户的信息:

<select th:onclick="javascript:doAction(' + @{/userInfo} + '?name=this.options[this.selectedIndex].value' + ')">
  <option value="John">John</option>
  <option value="Sam">Sam</option>
</select>

请求的查询:

http://server:port/userInfo?name=John

@RequestMapping(value = "/userInfo", method=RequestMethod.GET)
public String processForm(String name) {
  System.out.print(user); // "John"
}

但它不起作用。 :(
您能帮我解决这个问题吗?

【问题讨论】:

  • 不工作是什么意思? :) 你能在浏览器中看到 HTTP 请求吗?
  • 是的,完全是:-(什么都没有发生。我不确定,如果语句“javascript:doAction”是正确的,因为在我点击“选择”中的“选项”后什么都没有发生,你知道如果某个触发器已启动。
  • 我不是 thymeleaf 方面的专家,但是客户端生成了哪些 HTML/JS 代码?你看到 JS 控制台有什么问题吗?

标签: javascript spring-mvc thymeleaf


【解决方案1】:

我认为您可能对这部分有疑问:

th:onclick="javascript:doAction(' + @{/userInfo} + ' name=this.options[this.selectedIndex].value' + ')"

你检查过 Thymeleaf 生成了什么吗?

但是。这是一个关于如何在每次选择更改时使用一些 jQuery 来触发请求的想法:

$('#users').on('change', function(){
    var url = $(this).data('url') + "?name=" + $('#users option:selected').val();
    $('#result').html(url);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id="users" data-url="/userInfo">
    <option value="John">John</option>
    <option value="Sam">Sam</option>
</select>

<p id="result"></p>

在这个 sn-p 中,我只是打印您在帖子中建议的 URL,但您明白了。使用 Thymeleaf,您可以将 data-url="/userInfo" 替换为 th:attr="data-url=@{/userInfo}"

另外,您的方法processForm(String name) 可能有问题。 变量name 是一个请求参数,所以你需要注释它,例如:

@RequestMapping(value = "/userInfo", method=RequestMethod.GET)
public String processForm(@RequestParam(value = "name", required = true) String name) {
    System.out.print(user); // "John"
}

【讨论】:

    猜你喜欢
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多