美文网首页
thymeleaf实现ajax请求的两种方式

thymeleaf实现ajax请求的两种方式

作者: tinyvampirepudg | 来源:发表于2021-09-18 23:32 被阅读0次

注意,对应的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

项目地址

tinytongtong / spring-thymeleaf

相关文章

网友评论

      本文标题:thymeleaf实现ajax请求的两种方式

      本文链接:https://www.haomeiwen.com/subject/hecugltx.html