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:
JavaScript
x
19
19
1
<script th:inline="javascript">
2
$(function() {
3
$('#querySubmit').click(querySubmitClickAction);
4
querySubmit.addEventListener('click', querySubmitClickAction);
5
function querySubmitClickAction(e) {
6
7
var theSize = 10;
8
var name = $(this).val();
9
$.ajax({
10
url: /*
11
[[@{/registeredUserList(type=0,userName=defaultName,page=0,size=10)}]]*/ 'dummy',
12
type: 'POST',
13
success: function (data) {
14
$(".table_content").html(data);
15
}
16
})
17
}
18
});
19
How can I make up the url using the variable in the [[]].
JavaScript
1
2
1
url: /*[[@{/registeredUserList(type=0,userName=name,page=0,size=theSize)}]]*/ 'will show error',
2
It’s will show error. How can I use the js variable put in the [[]].
Thank you very much.
Advertisement
Answer
You can do it like this:
JavaScript
1
20
20
1
<script th:inline="javascript">
2
/*<![CDATA[*/
3
4
// JavaScript variable
5
var theSize = 10;
6
7
// URL from Thymeleaf, note the round brackets to avoid that / becomes /
8
var theUrl = "[(@{/users/})]";
9
10
// Create an URL object resolving the relative url
11
var url = new URL(theUrl, document.location);
12
13
// Update the query parameters of the URL with the JavaScript variables
14
url.searchParams.append("size", theSize);
15
16
console.log(url);
17
18
/*]]>*/
19
</script>
20
In the JavaScript console, this prints:
http://localhost:3000/users/?size=10