使用Thymeleaf时,ajax的url如何设置?

使用Thymeleaf时,ajax的url如何设置?

最近在做一个论坛项目使用到了Thymeleaf,在使用ajax请求的时候发现无法获取BasePath。在经过一番查阅资料后终于得知如下俩种方法,在此记录以免以后用到。

在js中如果想使用Thymeleaf,必须要在<script>中加入th:inline="javascript"属性值表示可以使用内联 js ,即可以在 js 代码中使用 [[]] 取值,否则报错。即能够可靠的实现:

<script  type="text/javascript" th:inline="javascript">
</script>

实现方法1:

<script type="text/javascript" th:inline="javascript">
        /*<![CDATA[*/
 
        var basePath = [[${#httpServletRequest.getScheme() + "://" + #httpServletRequest.getServerName() + ":" + #httpServletRequest.getServerPort() + #httpServletRequest.getContextPath()}]];
 
        $(document).ready(function () {
            $.ajax({
                type: 'post',
                dataType: 'text',
                url: basePath + '/index/ajaxtest',
                data: {},
                cache: false,
                async: true,
                success: function (data) {
                    var data = eval('(' + data + ')');
                    $('#idUser').text(data.name);
                    $('#idMsg').text(data.msg);
                }
            });
        });
 
        /*]]>*/
    </script>

实现方法2:使用 url:/*[[@{/index/ajaxtest}]]*/这样就可以,不用那样获取basePath。

猜你喜欢

转载自www.cnblogs.com/zhangruifeng/p/12347419.html
今日推荐