表单元素转JSON
自定义一个函数
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
ajax提交表单
$.ajax({
type : "POST",
url : "rest/role/new",
dataType : "json",
data : $("#form_add_roleRecord").serializeObject(),
success : function(data) {
alert("成功");
},
error : function(data) {
alert("失败");
console.log(data);
}
});
java后台接收
我的后台使用了spring mvc
//模型
public class Role {
private Long id;
private String roleName;
private String roleSign;
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName == null ? null : roleName.trim();
}
public String getRoleSign() {
return roleSign;
}
public void setRoleSign(String roleSign) {
this.roleSign = roleSign == null ? null : roleSign.trim();
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
@Override
public String toString() {
return "Role [id=" + id + ", roleName=" + roleName + ", roleSign=" + roleSign + ", description=" + description + "]";
}
}
//控制器
@Controller
@RequestMapping(value = "/role")
public class RoleController {
@RequestMapping(value = "/new", method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
@ResponseBody
public String newRecord(Role role, HttpServletRequest request) {
try {
System.out.println(role.toString());
} catch (Exception e) {
e.printStackTrace();
}
return "{\"success\":\"true\"}";
}
}
//输出
Role [id=null, roleName=testaa, roleSign=user:create, description=]