Skip to content

How can I put the variable in the inline javascript [[]] api path

I have a question, I need make up the url in the javasctipt. But I don’t known how to put the variable in the th:inline=”javascript” . My code below:

 <script th:inline="javascript">
 $(function() {
    $('#querySubmit').click(querySubmitClickAction);
    querySubmit.addEventListener('click', querySubmitClickAction);
    function querySubmitClickAction(e) {
        
        var theSize = 10;
        var name = $(this).val();
        $.ajax({
            url: /* 
[[@{/registeredUserList(type=0,userName=defaultName,page=0,size=10)}]]*/ 'dummy',
            type: 'POST',
            success: function (data) {
                $(".table_content").html(data);
            }
        })
     }
  });

How can I make up the url using the variable in the [[]].

 url: /*[[@{/registeredUserList(type=0,userName=name,page=0,size=theSize)}]]*/ 'will show error',

It’s will show error. How can I use the js variable put in the [[]].

Thank you very much.

Answer

You can do it like this:

<script th:inline="javascript">
    /*<![CDATA[*/

    // JavaScript variable
    var theSize = 10;

    // URL from Thymeleaf, note the round brackets to avoid that / becomes /
    var theUrl = "[(@{/users/})]";

    // Create an URL object resolving the relative url
    var url = new URL(theUrl, document.location);

    // Update the query parameters of the URL with the JavaScript variables
    url.searchParams.append("size", theSize);

    console.log(url);

    /*]]>*/
</script>

In the JavaScript console, this prints:

http://localhost:3000/users/?size=10