如何在Thymeleaf中實現ajax請求url的可靠構造?

版權聲明:本文爲博主原創文章,但是你也可以隨意轉載。 https://blog.csdn.net/smartcore/article/details/77017122

作爲一個應用型碼蟻,對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://blog.csdn.net/smartcore/article/details/52121676,感覺原先在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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章