ajax json 提交 java_ajax 以json形式提交表单

表单元素转JSON

b67893a81007a11abc95b8a075451860.png

自定义一个函数

$.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=]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值