java - Spring MVC @ModelAttribute 未填充 AJAX Post 请求
问题描述
当我尝试使用 Ajax Post 请求将数据发送到我的控制器时,我的 @ModelAttribute 对象不会被填充。但是当我使用表单提交发送值时,它工作正常。请检查下面的代码,
形式,
<form action="#" id="productForm" th:action="@{/save}" th:object="${product}" method="POST">
<table>
<tbody>
<tr>
<td>Name:</td>
<td><input id="name" type="text" th:field="*{name}" /></td>
</tr>
<tr>
<td>Brand:</td>
<td><input id="brand" type="text" th:field="*{brand}" /></td>
</tr>
<tr>
<td>Made In:</td>
<td><input id="madeIn" type="text" th:field="*{madeIn}" /></td>
</tr>
<tr>
<td>Price:</td>
<td><input id="price" type="text" th:field="*{price}" /></td>
</tr>
</tbody>
</table>
<br />
<button type="submit">Save</button>
<button type="button" onclick="saveWithAjaxPost();">Save with Ajax Post</button>
</form>
控制器,
@RequestMapping(value = "/saveWithAjaxPost", method = RequestMethod.POST)
@ResponseBody
public ModelMap saveWithAjaxPost(@ModelAttribute Product product) {
ModelMap model = new ModelMap();
service.saveProduct(product);
model.put("MESSAGE", "Success");
return model;
}
JavaScript,
function saveWithAjaxPost(){
var params = $("#productForm").serialize();
$.ajax({
url:"/saveWithAjaxPost",
type:"POST",
contentType:"application/json",
data:params,
async:true,
dataType:"json",
success:function(response){
$('#productsListDiv').empty();
getAllProcucts();
},
error:function(response){
alert(response.message);
}
});
}
我"name=test_name&brand=test_brand&madeIn=test_made_in&price=1000"
在序列化表格后得到。
这一定是一个非常简单的错误,但我无法弄清楚我在这里做错了什么......可能是什么问题?
解决方案
推荐阅读
- java - Play Framework sbt 程序集 jar 运行错误:-“未提供根服务器路径”
- git - 在本地提交代码后如何撤消代码更改?
- javascript - 粘性滚动小部件
- php - sql + php-在插入前检查重复
- android - 如何允许用户输入一次“A”字母?
- dialogflow-es - Dialogflow REST API 用于获取意图的用户话语
- reactjs - 如何获取位于 React 应用程序外部的输入值?
- provisioning-profile - 配置文件不包括 beta-reports-active 权利
- javascript - 无法在第二个或第三个删除的动态元素上触发 CK 编辑器 - CkEditor
- c++ - 数组:如何在指定索引之前显示数组的第一个和最后一个元素以及数组元素的差异?