ajax 以json形式提交表单

前端之家收集整理的这篇文章主要介绍了ajax 以json形式提交表单前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

表单元素转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=]
原文链接:https://www.f2er.com/ajax/162450.html

猜你在找的Ajax相关文章