1、serialize()把表单的值序列化成字符串
1 <html> 2 <head> 3 <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> 4 </head> 5 <body> 6 <p id="results"><b>Results: </b> </p> 7 <form> 8 <select name="single-name"> 9 <!--这一段序列化为字符串的结果是:name=text 在这里,默认选中的是Single1——> single-name=Single1--> 10 <option>Single1</option> 11 <option>Single2</option> 12 </select> 13 <select name="multiple-name" multiple="multiple"> 14 <!--这一段序列化为字符串的结果是:name=text 在这里——> multiple-name=Multiple1&multiple-name=Multiple3--> 15 <option selected="selected">Multiple1</option> 16 <option>Multiple2</option> 17 <option selected="selected">Multiple3</option> 18 </select><br/> 19 <input type="checkbox" name="check-name" value="check1" checked="checked"/> check1111 20 <!--这一段序列化为字符串的结果是:name=value——>check-name=check1--> 21 <input type="checkbox" name="check-name" value="check2" checked="checked"/> check2222 22 <!--这一段序列化为字符串的结果是:name=value——>chec-namek=check2--> 23 <input type="radio" name="radio-name" value="radio1" checked="checked"/> radio1111 24 <!--这两段只能同时选中一个,序列化为字符串的结果是:name=value——>radio-name=radio1--> 25 <input type="radio" name="radio-name" value="radio2" checked="checked"/> radio2222 26 </form> 27 <script> 28 $("#results").append( "<tt>" + $("form").serialize() + "</tt>" ); 29 </script> 30 </body> 31 </html>
最终序列化成字符串的结果是:single-name=Single1&multiple-name=Multiple1&multiple-name=Multiple3&check-name=check1&check-name=check2&radio-name=radio2 2、serializeArray()把表单的值序列化成JSON对象,是对象哦
1 <html> 2 <head> 3 <meta charset="utf-8"> 4 <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> 5 </head> 6 <body> 7 <p id="results"><b>Results: </b> </p> 8 9 <form> 10 <select name="single"> 11 <option>Single</option> 12 <option>Single2</option> 13 </select> 14 <select name="multiple" multiple="multiple"> 15 <option selected="selected">Multiple</option> 16 <option>Multiple2</option> 17 <option selected="selected">Multiple3</option> 18 </select><br/> 19 <input type="checkbox" name="check" value="check1"/> check1 20 <input type="checkbox" name="check" value="check2" checked="checked"/> check2 21 <input type="radio" name="radio" value="radio1" checked="checked"/> radio1 22 <input type="radio" name="radio" value="radio2"/> radio2 23 </form> 24 <script> 25 var fields = $("select, :radio").serializeArray(); 26 jQuery.each( fields, function(i, field){ 27 alert(JSON.stringify(field)); 28 $("#results").append(field.value +" "); 29 }); 30 </script> 31 </body> 32 </html>
时间: 2024-10-06 10:54:41