js將form表單序列化[json字符串、數組、對象]

1.序列化爲字符串ajax

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

2.序列化爲數組後端

  var formData=$("#form").serializeArray();//[Object, Object, Object] 數組

自定義參數補充post

  formData.push({"name": "psid", "value": $("#psid").val()});this

3.序列化爲對象url

    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傳遞普通數組 spa

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 = [];
        }
    }
});

後端代碼code

public AjaxResult deleteNum(String[] deleteNum){
    AjaxResult ajaxResult = new AjaxResult();
    //這個時候已經獲得了deleteNum數組值
    return ajaxResult;
}

5.form表單提交自定義對象數組 orm

<form id="form" name="form"  method="post">
 <input type="hidden" name="table" value="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(); 
}
相關文章
相關標籤/搜索