serializeArray()
将用作提交的表单元素的值编译成拥有name和value对象组成的数组。例如[{name: a value: 1},{name: b value: 2},...]
.serializeArray()
这个方法不接受任何参数。
.serializeArray()
方法创建一个对象组成的javascript数组,用来编码成一个JSON一样的字符串。它对表单和/或表单控件的 jQuery 集合起作用。该控件可以有以下几种类型:
<form> <div><input type="text" name="a" value="1" id="a" /></div> <div><input type="text" name="b" value="2" id="b" /></div> <div><input type="hidden" name="c" value="3" id="c" /></div> <div> <textarea name="d" rows="8" cols="40">4</textarea> </div> <div><select name="e"> <option value="5" selected="selected">5</option> <option value="6">6</option> <option value="7">7</option> </select></div> <div> <input type="checkbox" name="f" value="8" id="f" /> </div> <div> <input type="submit" name="g" value="Submit" id="g" /> </div> </form>
.serializeArray()
方法使用标准的W3C"successful controls"的标准来检测哪些元素应当包括在内。被禁用的元素不会被包括在内。并且,元素必须含有name
属性。此外,提交按钮的值也不会被序列化。文件选择元素的数据也不会被序列化。不包含value
属性的元素用空字符串值表示。
.serializeArray()
方法可以对单独选择的表单控件的jQuery对象进行操作,比如<input>
,<textarea>
,和<select>
。还有个更方便的方法是,直接使用<form>
标签来进行序列化操作:
$('form').submit(function () { console.log($(this ).serializeArray());return false; });
这将产生以下数据结构(浏览器提供的console.log
):
[ { name: "a", value: "1" }, { name: "b", value: "2" }, { name: "c", value: "3" }, { name: "d", value: "4" }, { name: "e", value: "5" } ]
例子
从表单获取值,遍历并且显示他们
<!DOCTYPE html> <html> <head> <style> body, select { font-size:14px; } form { margin:5px; } p { color:red; margin:5px; } b { color:blue; } </style> <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script> </head> <body> <p><b>Results:</b> <span id="results"></span></p> <form> <select name="single"> <option>Single</option> <option>Single2</option> </select> <select name="multiple" multiple="multiple"> <option selected="selected">Multiple</option> <option>Multiple2</option> <option selected="selected">Multiple3</option> </select><br/> <input type="checkbox" name="check" value="check1" id="ch1"/> <label for="ch1">check1</label> <input type="checkbox" name="check" value="check2" checked="checked" id="ch2"/> <label for="ch2">check2</label> <input type="radio" name="radio" value="radio1" checked="checked" id="r1"/> <label for="r1">radio1</label> <input type="radio" name="radio" value="radio2" id="r2"/> <label for="r2">radio2</label> </form> <script>function showValues() {var fields = $(":input").serializeArray(); $("#results").empty(); jQuery.each(fields,function (i, field){ $("#results").append(field.value + " "); }); } $(":checkbox, :radio").click(showValues); $("select").change(showValues); showValues(); </script> </body> </html>
Results: