标签:
举例:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $(document).ready(function(){ personObj = new Object(); personObj.firstname = "John"; personObj.lastname = "Doe"; personObj.age = 50; personObj.eyecolor = "blue"; $("button").click(function(){ $("div").text($.param(personObj)); }); }); </script> </head> <body> <button>Serialize object</button> <div></div> </body> </html>
上述返回的结果是:firstname=John&lastname=Doe&age=50&eyecolor=blue
$.param将对象或者数组序列化,序列化的值可以用于AJAX请求时的URL查询字符串
$.param(object,trad)
Parameter | Description |
---|---|
object | 必须,指定一个要被序列化的对象亦或数组 |
trad |
可选,是否使用传统的参数序列化模式,默认false,注意要在jQuery1.4以上才能使用 |
$(document).ready(function(){ personObj ={ a: { one: 1, two: 2, three: 3 }, b: [ 1, 2, 3 ] } $("button").click(function(){ document.body.innerHTML=(decodeURIComponent($.param(personObj,true))); }); });
上述传统序列化显示的结果是:a=[object+Object]&b=1&b=2&b=3
如果是
$("div").text(decodeURIComponent($.param(personObj)));
将true去掉,将成为a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("div").text($("form").serialize()); }); }); </script> </head> <body> <form action=""> First name: <input type="text" name="FirstName" value="Mickey"><br> Last name: <input type="text" name="LastName" value="Mouse"><br> </form> <button>Serialize form values</button> <div></div> </body> </html>
结果是:FirstName=Mickey&LastName=Mouse
$(selector).serialize()
序列化表单值并创建一个编码过的url文本
你可以选择一个或更多的表单元素(比如input和textarea),或者表单元素本身
序列化的值可以被用于在创建一个AJAX请求的时候,组合URL查询字符串
将表单元素序列化成对象数组
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ var x = $("form").serializeArray(); console.log(x); }); }); </script> </head> <body> <form action=""> First name: <input type="text" name="FirstName" value="Mickey"><br> Last name: <input type="text" name="LastName" value="Mouse"><br> </form> <button>Serialize form values</button> <div id="results"></div> </body> </html>
控制台输出的结果是
语法格式为:
$(selector).serializeArray()
标签:
原文地址:http://www.cnblogs.com/RachelChen/p/5433734.html