注意,对应的Controller类不能使用@RestController
注解。
使用fragment
1、布局中定义fragment和id,定义ajax请求
<body>
...
<div>
<h3>get请求</h3>
<p>
<button onclick="executeGetAjax('眼里有光,心里有梦')" type="button">发起ajax-get请求</button>
</p>
<div th:fragment="get-response" th:id="id-request-get">
<p th:text="${value_get}"></p>
</div>
</div>
<script type="text/javascript">
function executeGetAjax(name) {
<!-- data中传递json对象 -->
$.ajax({
url: '/execute/get-ajax1',
type: 'get',
async: true,
data: {
name
},
dataType: 'text',
success: function (data) {
alert(data);
console.log(data);
$("#id-request-get").html(data);
}
})
};
</script>
</body>
2、WebController中定义对应的ajax请求方法
/**
* ajax请求,get-同步更新页面内容
*
* @param name
* @return
*/
@RequestMapping(value = "/execute/get-ajax", method = {RequestMethod.GET})
public String executeGet(Model model, @RequestParam(value = "name", required = false, defaultValue = "猫了个咪") String name) {
model.addAttribute("value_get", "get ajax response:" + name);
return "request-methods::get-response";
}
具体参考:
https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#rendering-template-fragments
使用ModelAndView
布局方式同fragment方式,webController方法中有改动:
/**
* 使用 ModelAndView 实现ajax请求
* @param model
* @param name
* @return
*/
@RequestMapping(value = "/execute/get-ajax1", method = {RequestMethod.GET})
public ModelAndView executeGet1(Model model, @RequestParam(value = "name", required = false, defaultValue = "猫了个咪") String name) {
model.addAttribute("value_get", "get ajax response:" + name);
return new ModelAndView("request-methods::get-response");
}
具体参考:
https://stackoverflow.com/questions/20982683/spring-mvc-3-2-thymeleaf-ajax-fragments