在ajax中有 serializeArray()方法 可以将form表单中的数据序列化成如下的格式
[
{
name: "a",
value: "1"
},
{
name: "b",
value: "2"
},
{
name: "c",
value: "3"
},
{
name: "d",
value: "4"
},
{
name: "e",
value: "5"
}
]
但是有时候,我们需要将form表单序列化成对象的格式,那么封装一个简单的函数便会更简单
$.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;
};
可以使用这个方法直接将from表单中的数据序列化成如下的对象格式
{
name:1,
age:11,
weight:60
}