如何在Thymeleaf中实现ajax请求url的可靠构造?
作为一个应用型码蚁,对jstl、freemaker、thymeleaf等等众多深感无奈…… 建立springboot应用时,模板中有一项是thymeleaf,springboot现在也是推荐使用这个,然而并没有时间仔细研究它…… 现在的问题是,ajax请求时,如何可靠的构造url? 先说本文的结论,在xxx.html文件中,加入以下的类似代码,即能够可靠的实现: <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>
其他问题: 1、本文说的“可靠”,主要是指无论你是测试还是生产,或者修改根路径等,均不影响ajax请求的正确性; 2、当前找到的技术文主要是强调在html文件中使用ajax进行请求,但实操时,我们多半是在外部的js文件中进行ajax请求,此时,折中的方案就是在相关的js文件中,引用上面在html文件中定义的basePath变量,来构造完整的url; 另外一种仅是为了实现模块化的方案是,将需要thymeleaf解析的变量定义放在一个单独的fragment类型的html文件中,如以下: // 以下是fragscript.html中的内容 // 假设fragscript.html与index.html文件在一个目录下(index.html详细见本文结尾的demo里) <script th:fragment="outerJs01" xmlns:th="http://www.springframework.org/schema/mvc" type="text/javascript" th:inline="javascript"> /*<![CDATA[*/ var basePath02 = /*[[${#httpServletRequest.getScheme() + "://" + #httpServletRequest.getServerName() + ":" + #httpServletRequest.getServerPort() + #httpServletRequest.getContextPath()}]]*/; /*]]>*/ </script> 然后,在index.html文件的</body>之后,使用如下代码引用上面的fragment: <script th:replace="fragscript :: outerJs01"></script> 3、本文其实是基于作者的另外一篇文章:http://www.52php.cn/article/p-bpufvrcr-bkq.html,感觉原先在eclipse里创建jsp页面时,自动生成的basePath真心有用啊,不知道为什么现在用的越来越少了,也有可能是我不会用当前新产品的缘故吧 一些相关的链接(作者并没有参考其中): springMVC+thymeleaf怎么做ajax提交:http://bbs.csdn.net/topics/391957407 Thymeleaf for a URL in Javascript code? https://stackoverflow.com/questions/40670352/thymeleaf-for-a-url-in-javascript-code How to Use Thymeleaf for a URL in Javascript code? http://forum.thymeleaf.org/Make-Ajax-Call-using-Thymeleaf-Spring-WebFlow-Jquery-WITHOUT-using-the-now-deprecated-spring-js-dojos-td4028308.html 附一个简单的demo(CSDN竟然默认至少要收1个积分): http://download.csdn.net/download/smartcore/9926870 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |