首页 > 代码库 > javascript-js将form表单序列化[json字符串、数组、对象]

javascript-js将form表单序列化[json字符串、数组、对象]

1.序列化为字符串

$("#Form").serialize();//name=zhangsan&sex=1&age=20  

2.序列化为数组

  $("#form").serializeArray();//[Object, Object, Object] 

3.序列化为对象

    function getFormJson(form) {        var o = {};        var a = $(form).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;    }

4.ajax传递普通数组 

var deleteNum= [];//定义要传递的数组deleteNum.push("1");deleteNum.push("2");deleteNum.push("3");//向数组中添加元素$.ajax({    type:"post",    url:"deleteNum.do",    data:{deleteNum:deleteNum},    traditional: true,//必须指定为true    success:function(data){        if(data.success){            deleteNum = [];        }    }});

后端代码

public AjaxResult deleteNum(String[] deleteNum){    AjaxResult ajaxResult = new AjaxResult();    //这个时候已经得到了deleteNum数组值    return ajaxResult;}

5.form表单提交自定义对象数组 

<form id="form" name="form"  method="post">
 <input type="hidden" name="table" value="http://www.mamicode.com/user">
<table> <tr> <td><input type="text" name="userList[0].name"/></td> <td><input type="text" name="userList[0].password"/></td> </tr> <tr> <td><input type="text" name="userList[1].name"/></td> <td><input type="text" name="userList[1].password"/></td> </tr> <tr> <td><input type="text" name="userList[2].name"/></td> <td><input type="text" name="userLIst[2].password"/></td> </tr> </table></form>

ajax提交

$("#form").serializeArray()

后端接收

    public class FormList {        private String table;        private ArrayList<User> userlist;                public String getTable() {            return table;        }        public void setTable(String table) {            this.table = table;        }        public ArrayList<User> getUserlist() {            return userlist;        }        public void setUserlist(ArrayList<User> userlist) {            this.userlist= userlist;        }    }
public AjaxResult saveUpdateUser(FormList list){    List<User> userlist = list.getUserlist(); }

 










javascript-js将form表单序列化[json字符串、数组、对象]