form表单序列化之后追加字段
在需要提交表单的模块,我们往往需要用到序列化表单并通过ajax实现交互。如果遇上特殊的需求,在表单的数据之外,还需要传送一些比较重要的字段,或数据,我们可以采取下列方法:
var data = $.param({'state': state}) + '&' + $('#desProForm').serialize();
完整代码:
页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../JQuery/jquery-3.2.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submitButton").click(function(){
var data = $.param({"id":"1"}) + "&" + $("#testForm").serialize() + "";
$.ajax({
type:"POST",
data:data,
url:"${pageContext.request.contextPath }/Test/saveUser.do",
success:function(data){
console.log(data);
}
});
});
});
</script>
<title>Insert title here</title>
</head>
<body>
<form id="testForm">
<table>
<tr>
<td><label for="userName">用户名:</label></td>
<td><input id="userName" name="userName" type="text"></td>
</tr>
<tr>
<td><label for="password">密码:</label></td>
<td><input id="password" name="password" type="password"></td>
</tr>
<tr>
<td> </td>
<td><input id="submitButton" type="button" value="提交"></td>
</tr>
</table>
</form>
</body>
</html>
效果:
后台:
@RequestMapping("saveUser.do")
public ResponseEntity<Map<String,Object>> saveUser(String id, User user){
ap<String,Object> map = new HashMap<String,Object>();
System.out.println(id + " " + user);
map.put("status", "success");
return new ResponseEntity<Map<String,Object>>(map,HttpStatus.OK);
}
效果:
Reference:
[1] 大园子, form表单序列化之后追加字段, https://www.cnblogs.com/eoooxy/p/6341609.html