zhangruifeng

使用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。

试用这种方法编译器可能会报错,但是可以忽略此错误,直接运行即可。

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-24
  • 2022-12-23
  • 2022-12-23
  • 2022-01-04
  • 2021-04-19
  • 2021-10-08
猜你喜欢
  • 2022-02-10
  • 2022-12-23
  • 2021-12-19
  • 2021-10-21
  • 2022-12-23
  • 2021-09-02
  • 2021-10-10
相关资源
相似解决方案