簡體   English   中英

如何使用Ajax將表單數據發送到Spring控制器

[英]How to send form data to a Spring controller using ajax

我有一個用百里香生成的Sudoku板,我想將所有平鋪值作為雙精度數組發送到Spring控制器或作為字符串發送。

<form class="box" id="sudokuBoard">
        <table>
            <tr th:each="row: ${board}">
                <td th:each="value: ${row}">
                    <div th:switch="${value}">
                        <input th:case="0" style="width:30px;height:30px;text-align:center" type = "text" maxlength="1" value="0">
                        <input th:case="*" style="width:30px;height:30px;text-align:center;background-color:lightgreen" type = "text" th:value="${value}" readonly>
                    </div>
                </td>
            </tr>
        </table>

        <input type="submit"> Check Solution </input>
    </form>

我試圖使用serialize()函數,但是它不發送任何東西,或者我做錯了什么。

<script>
        $("#sudokuBoard").submit(function(e) {

            e.preventDefault(); // avoid to execute the actual submit of the form.

            var form = $(this);

            $.ajax({
                type: "POST",
                url: "/sudoku",
                dataType: 'json',
                data: form.serialize(),
                success: function(msg)
                {
                    console.log("data sent");
                }
            });
        });
    </script>

這是Spring控制器

@RequestMapping(value = "/sudoku", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    String checkBoardStatus(@RequestBody String jsonString){
        System.out.println("json string: " + jsonString);
        return "sudoku";
    }

您可以使用此示例,其中成功將是您的回調方法

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: function(result) {},
  dataType: dataType
});
@RequestMapping(value = "/sudoku", method = RequestMethod.POST)
String checkBoardStatus(Map<String,Object> params){
    System.out.println("Request Params: " + params);
    return "sudoku";
}

用戶上面的代碼。嘗試使用DTO類來映射請求正文而不是Map,並且不要使用@RequestBody注釋

暫無
暫無

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

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