.serializeArray()

.serializeArray() 方法创建一个对象组成的javascript数组用来编码成一个JSON一样的字符串。 它对表单 和/或 表单控件的 jQuery 集合起作用。

描述: 将用作提交的表单元素的值编译成拥有name和value对象组成的数组。例如[ { name: a value: 1 }, { name: b value: 2 },...]

.serializeArray()方法使用标准的W3C"successful controls"的标准来检测哪些元素应当包括在内。被禁用的元素不会被包括在内。并且,元素必须含有 name 属性。此外,提交按钮的值也不会被序列化。文件选择元素的数据也不会被序列化。

 1 <form>
 2   <div><input type="text" name="a" value="1" id="a" /></div>
 3   <div><input type="text" name="b" value="2" id="b" /></div>
 4   <div><input type="hidden" name="c" value="3" id="c" /></div>
 5   <div>
 6     <textarea name="d" rows="8" cols="40">4</textarea>
 7   </div>
 8   <div><select name="e">
 9     <option value="5" selected="selected">5</option>
10     <option value="6">6</option>
11     <option value="7">7</option>
12   </select></div>
13   <div>
14     <input type="checkbox" name="f" value="8" id="f" />
15   </div>
16   <div>
17     <input type="submit" name="g" value="Submit" id="g" />
18   </div>
19 </form>
View Code
1 $('form').submit(function() {
2   console.log($(this).serializeArray());
3   return false;
4 });
View Code
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4   <style>
 5   body, select { font-size:14px; }
 6   form { margin:5px; }
 7   p { color:red; margin:5px; }
 8   b { color:blue; }
 9   </style>
10   <script src="http://code.jquery.com/jquery-latest.js"></script>
11 </head>
12 <body>
13   <p><b>Results:</b> <span id="results"></span></p>
14  
15   <form>
16     <select name="single">
17       <option>Single</option>
18       <option>Single2</option>
19  
20     </select>
21     <select name="multiple" multiple="multiple">
22       <option selected="selected">Multiple</option>
23       <option>Multiple2</option>
24  
25       <option selected="selected">Multiple3</option>
26     </select><br/>
27     <input type="checkbox" name="check" value="check1" id="ch1"/>
28  
29     <label for="ch1">check1</label>
30     <input type="checkbox" name="check" value="check2" checked="checked" id="ch2"/>
31  
32     <label for="ch2">check2</label>
33     <input type="radio" name="radio" value="radio1" checked="checked" id="r1"/>
34  
35     <label for="r1">radio1</label>
36     <input type="radio" name="radio" value="radio2" id="r2"/>
37  
38     <label for="r2">radio2</label>
39   </form>
40 <script>
41   function showValues() {
42     var fields = $(":input").serializeArray();
43     $("#results").empty();
44     jQuery.each(fields, function(i, field){
45       $("#results").append(field.value + " ");
46     });
47   }
48  
49   $(":checkbox, :radio").click(showValues);
50   $("select").change(showValues);
51   showValues();
52 </script>
53  
54 </body>
55 </html>
View Code
原文地址:https://www.cnblogs.com/dobestself-994395/p/4363129.html