使用Ajax提交HTML表单至Java REST API失败,请求排查错误
作为JavaScript和jQuery领域的新手,在项目中尝试通过Ajax传递HTML表单数据时遇到问题。点击提交按钮后抛出异常:Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
以下是相关代码详情:
index.html
<!DOCTYPE HTML> <html> <title>Datasheet Generation</title> <head> <link rel = "stylesheet" href= "css_for_index.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet"> <script type = "text/javascript"> function callvalue(){ var formData = JSON.stringify($(#myForm).serializeArray()); $.ajax({ type: "POST", url: "http://localhost:8080/", data: formData, success: function(){ console.log(formData); }, error: function (error) { console.log(`Error ${error}`); }, dataType: "json", contentType : "application/json" }); } </script> </head> <body> <form id = "myForm" method = "post" onsubmit= "callvalue()"> <table class="table"> <tr> <td>Revision :</td> <td><input type = "text" id="revision"/></td> </tr> <tr> <td>Project Name :</td> <td><input type = "text" id="projectName"/></td> </tr> <tr> <td>Product Description :</td> <td><input type = "text" id="prodDesc"/></td> </tr> <tr> <td>Product Code :</td> <td><input type = "text" id="prodCode"/></td> </tr> <tr> <td>Packing :</td> <td><input type = "text" id="packing"/></td> </tr> </table> <br> <button class="Gen_Button" type="submit">Generate Datasheet</button> </form> </body> </html>
Controller类
@RestController public class DataSheetGenController { @PostMapping(value ="/submit", consumes = MediaType.APPLICATION_JSON_VALUE) public String getProject(@RequestBody Project project) { System.out.println("Hello"); return "submit"; } }
Model类
public class Project { private String revision; private String projectName; private String prodDesc; private String prodCode; private String packing; public String getRevision() { return revision; } public void setRevision(String revision) { this.revision = revision; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getProdDesc() { return prodDesc; } public void setProdDesc(String prodDesc) { this.prodDesc = prodDesc; } public String getProdCode() { return prodCode; } public void setProdCode(String prodCode) { this.prodCode = prodCode; } public String getPacking() { return packing; } public void setPacking(String packing) { this.packing = packing; } }
问题排查与修复方案
1. 请求URL不匹配
前端Ajax请求的URL是http://localhost:8080/,但后端Controller通过@PostMapping("/submit")映射的路径是/submit,导致请求找不到对应处理方法。
修复:将Ajax的url修改为"http://localhost:8080/submit"。
2. jQuery选择器语法错误
代码中$(#myForm)缺少引号,jQuery选择器必须用引号包裹元素ID。
修复:改为$("#myForm")。
3. 表单元素缺少name属性
serializeArray()依赖表单元素的name属性来序列化数据,当前input仅设置了id,没有name,导致无法正确生成对应Project类的JSON数据。
修复:给每个input添加与Project类字段名一致的name属性,例如:
<input type = "text" id="revision" name="revision"/> <input type = "text" id="projectName" name="projectName"/> <!-- 其他input同理添加name属性 -->
4. 未阻止表单默认提交行为
点击submit按钮后,除了执行Ajax请求,表单会触发默认的同步提交行为,干扰Ajax请求的正常执行,甚至可能导致页面刷新。
修复:修改callvalue函数,末尾添加return false;,同时修改表单的onsubmit属性为onsubmit="return callvalue()":
function callvalue(){ var formData = JSON.stringify($("#myForm").serializeArray()); $.ajax({ type: "POST", url: "http://localhost:8080/submit", data: formData, success: function(){ console.log(formData); }, error: function (error) { console.log(`Error ${error}`); }, dataType: "json", contentType : "application/json" }); return false; // 阻止默认提交行为 }
<form id = "myForm" method = "post" onsubmit= "return callvalue()">
内容的提问来源于stack exchange,提问作者Abikrish

