簡體   English   中英

如何正確發送參數到控制器? (Thymeleaf + Javascript)

[英]How to send parametr to Controller properly? (Thymeleaf + Javascript)

我是 Thymeleaf 的初學者。 我所知道的是“Thymeleaf 不是 Javascript,它是在服務器上呈現的”這一事實。 我一直在犯錯誤,因為我通常嘗試像 JavaScript 一樣使用 Thymeleaf。

HTML

<form th:action="@{/user/sqlCode}" method="post">
    <button id="newDatabase"></button>
</form>
<textarea id="generatedSql" readonly></textarea>

控制器

@PostMapping(path = { "/user/sqlCode" })
public String createSchema(@RequestParam(???) String tmp) {
    String finallyMyValue = tmp;
    // STOP  I want to have data from generatedSql in this moment (finallyMyValue)
    // ...
}

@ 使命 @
1.點擊按鈕(id:newDatabase)
2.從textarea中獲取數據(id:generatedSql)
3. 將帶有該數據的值發送給控制器
4. 快樂:)
@ 使命 @

我嘗試了很多東西,但只使用 Javascript。 場景總是相同的,JavaScript 完全在 Thymeleaf 之前執行,最后我無法正確讀取該數據......我嘗試了這種場景:

  1. 單擊按鈕(id:newDatabase)
  2. 使用 JavaScript從 textarea (id:generatedSql)獲取數據
  3. 使用 JavaScript將該數據插入到輸入標簽中的變量name
  4. 將變量name發送到控制器。
  5. 在這里我總是得到 NULL 或錯誤 404

我失敗的方法的屏幕截圖,在斷點處以 null 結束: 在此處輸入圖片說明

我認為您應該嘗試在 Ajax 中使用 Javascript:

<div>
    <button type="button" onclick="submitData()">Change Content</button>
</div>

function submitData() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
        }
    };
    xhttp.open("post", "$URL", true);
    xhttp.send();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM