AjaxのDataをControllerで受け取りたい
JAVAの初学者で社員管理Webアプリのデモを作成しています。
非同期処理で社員情報を変更したいのですが、AjaxのDataがどうしてもnullになってしまいます。
実現したいこと
HTMLからuser_idを取得し、AjaxのDataに詰めて、Controllerの引数で受け取りたい。
ソース
Build.gradle
1plugins { 2 id 'org.springframework.boot' version '2.5.12' 3 id 'io.spring.dependency-management' version '1.0.11.RELEASE' 4 id 'java' 5} 6~中略~ 7 8dependencies { 9 implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 10 implementation 'org.springframework.boot:spring-boot-starter-jdbc' 11 implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' 12 implementation 'org.springframework.boot:spring-boot-starter-web' 13 implementation 'mysql:mysql-connector-java:8.0.20' 14 implementation 'org.springframework.boot:spring-boot-starter-validation' 15 implementation('org.webjars:jquery:3.5.1') 16 implementation('org.webjars:bootstrap:4.5.3') 17 implementation('org.webjars:webjars-locator:0.40') 18 implementation 'org.modelmapper:modelmapper:2.3.0' 19 compileOnly 'org.projectlombok:lombok' 20 developmentOnly 'org.springframework.boot:spring-boot-devtools' 21 runtimeOnly 'mysql:mysql-connector-java' 22 annotationProcessor 'org.projectlombok:lombok' 23 testImplementation 'org.springframework.boot:spring-boot-starter-test' 24}
html
1<tbody> 2 <form th:action="@{/Edit}" th:object="${List}" method="post"> 3 <tr th:each="list : ${List}"> 4 <td th:text="${list.user_id}" id="userId" th:value="${list.user_id}"></td> 5 //その他テーブル 6 <td> 7 <button onclick="Event()" >ボタン</button> 8 </td> 9 </tr> 10 </form> 11</tbody>
Controller
1@RestController 2public class Controller { 3 4 @PostMapping(path = "/edit") 5 public String retire(@RequestParam int user_id) { 6 //処理 7 return "html"; 8 } 9}
js
1function Event() { 2 if (!confirm('この操作は取り消せません。よろしいですか?')) { 3 var data = {user_id:$("#userId").val()} 4 $.ajax({ 5 url: '/edit', 6 type: 'post', 7 dataType: 'json', 8 data: data 9 }) 10 .done(function () { 11 alert('success!'); 12 }) 13 .fail(function () { 14 alert('fail!'); 15 }) 16 } 17}
エラー内容・試したこと
@RequestBody は「Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported」
@RequestParamは「Required request parameter 'user_id' for method parameter type int is not present」
@Controllrtと@RestControllrtの組み合わせや、
contentTypeをapplication/x-www-form-urlencodedにしてみたり、
JSON.stringify(data)にしてみたり、
data:[1] や data: {user_id:1}にしたりしましたがどうやってもnullになります。
HTMLのButtonでidやvalueにEL式でuser_idをいれてやると希望通り動きます。
練習内容がAjaxで非同期通信することなのですが、AjaxのDataで全て賄うのは難しいのでしょうか。
ご回答、よろしくお願いします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/05/08 11:59
2022/05/08 12:06
2022/05/08 12:43
2022/05/08 18:40
2022/05/09 01:33
2022/05/09 01:39
2022/05/09 04:02
2022/05/09 05:07
2022/05/09 05:47