如何从Thymeleaf向JavaScript传递表单及模型参数?
Got it, let's work through this. The core issue here is that you're trying to mix server-side Thymeleaf variables with client-side JavaScript context in a way that doesn't play nice with how each layer renders. Here's the correct approach to pass both the form object and your model's currentPage/selectedPageSize values to your JS function:
Correct Button Markup
First, use Thymeleaf's th:onclick attribute to properly inject your model variables into the JavaScript function call. This ensures the server-side values are rendered into the client-side code correctly. Also, change the button's type to button to prevent the default form submission—we'll let your JS function handle that after calculations:
<button id="searchButton" class="btn btn-default" type="button" th:onclick="sendSearchRequest(this.form, [[${currentPage}]], [[${selectedPageSize}]])"> Search </button>
Why This Works
th:onclicktells Thymeleaf to process the attribute value server-side, so[[${currentPage}]]and[[${selectedPageSize}]]will be replaced with their actual values from your model before the page renders.this.formcorrectly references the parent form of the button, since we're using it within the button's click context.
JavaScript Function Example
Now, your sendSearchRequest function can receive all three parameters, do your pagination calculations, then submit the form. You might want to add the calculated values as hidden inputs to the form so your backend can pick them up:
function sendSearchRequest(form, currentPage, selectedPageSize) { // Do your pagination calculations here // Example: Adjust the current page based on your logic const updatedPage = currentPage + 1; // Replace with your actual calculation // Add updated values as hidden inputs to the form const pageInput = document.createElement('input'); pageInput.type = 'hidden'; pageInput.name = 'currentPage'; pageInput.value = updatedPage; form.appendChild(pageInput); const sizeInput = document.createElement('input'); sizeInput.type = 'hidden'; sizeInput.name = 'selectedPageSize'; sizeInput.value = selectedPageSize; // Or your calculated size form.appendChild(sizeInput); // Submit the form to your backend form.submit(); }
Why Your Original Approaches Failed
- First approach: Putting the JS function in
th:actiondoesn't work because Thymeleaf renders the entire action string as a literal, sothis.formisn't evaluated in the correct client-side context when the form tries to submit. - Second approach: Using native
onclickwithoutth:onclickmeans Thymeleaf never processes the${currentPage}and${selectedPageSize}variables—they're just treated as plain text, so your JS sees them as undefined.
内容的提问来源于stack exchange,提问作者Andrey Redkovskiy

