在onclick方法上创建get方法

时间:2015-02-09 10:21:26

标签: javascript spring-mvc thymeleaf

当有人使用Thymeleaf和Spring点击'select'中的'option'元素时,我希望获得有关客户的信息:

<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"
}

但它不起作用。 :( 你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

我认为你可能会遇到这个部分的问题:

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

您是否检查过Thymeleaf生成的内容?

<强>然而即可。以下是关于如何使用jQuery在每次选择更改时触发请求的想法:

&#13;
&#13;
$('#users').on('change', function(){
    var url = $(this).data('url') + "?name=" + $('#users option:selected').val();
    $('#result').html(url);
});
&#13;
<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>
&#13;
&#13;
&#13;

在此代码段中,我只是打印您在帖子中建议的网址,但您明白了。使用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"
}