我喜欢这个库:https://github.com/macek/jquery-serialize-object(1.7KB 大小)
给定一个基本的 HTML 表单:
<form id="contact">
<input name="user[email]" value="jsmith@example.com">
<input name="user[pets][]" type="checkbox" value="cat" checked>
<input name="user[pets][]" type="checkbox" value="dog" checked>
<input name="user[pets][]" type="checkbox" value="bird">
<input type="submit">
</form>
.serializeObject — 将选定的表单序列化为 JavaScript 对象
$('form#contact').serializeObject();
//=> {user: {email: "jsmith@example.com", pets: ["cat", "dog"]}}
主要风格
push — 将值推送到数组
<input name="foo[]" value="a">
<input name="foo[]" value="b">
$("form").serializeObject();
//=> {foo: [a, b]}
固定 — 将值添加到指定索引处的数组
<input name="foo[2]" value="a">
<input name="foo[4]" value="b">
$("form").serializeObject();
//=> {foo: [, , "a", , "b"]}
named — 为指定的键添加一个值
<input name="foo[bar]" value="a">
<input name="foo[bof]" value="b">
<input name="hello" value="world">
$("form").serializeObject();
//=> {foo: {bar: "a", bof: "b"}, hello: "world"}
类似的库(更活跃):https://github.com/marioizquierdo/jquery.serializeJSON
类似的库(非常活跃):https://github.com/brainfoolong/form-data-json
使用最后一个,您不仅可以序列化数据,反之亦然:为表单字段设置值