jQuery - 序列化

创建时间:
2018-09-04 15:09
最近更新:
2018-09-04 15:09

.serialize()

version added: 1.0
Returns: String
Description: Encode a set of form elements as a string for submission.

将表单序列化为字符串形式: name1=value1&name2=value2&nameN&valueN...

The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements. The form elements can be of several types:

Tony测试记录:
下述 DOM,使用 $("form").serialize() 或删除 form 标记后改为 $("body>*").serialize() 均返回 a=1&b=2&c=3&d=4&e=5。如删除某个表单元素的 name,则返回的 String 中将不再包含此元素的 name=value 对。jQuery 选择到的集合中的 div 等非表单元素将自动忽略。

<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>

The .serialize() method can act on a jQuery object that has selected individual form elements, such as input, textarea, and select. However, it is typically easier to select the form tag itself for serialization:

$('form').submit(function() {
    alert($(this).serialize());
    return false;
});

This produces a standard-looking query string:

a=1&b=2&c=3&d=4&e=5

Warning: selecting both the form and its children will cause duplicates in the serialized string.

Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.

jQuery.com 上有 1 示例,未整理。

.serializeArray()

version added: 1.2
Returns: Array
Description: Encode a set of form elements as an array of names and values.

$("form").serializeArray() 返回一个数组,
此数组的每个成员都是一个对象,
每个对象均对应着表单中的一个元素,
每个对象有2个属性,
第1个属性名是name,对应表单元素的name;
第2个属性名是value,对应表单元素的value。
name与value属性的值,均为String类型,而不是Number等其它类型。
如某个表单元素没有value属性,则该表单元素对应的对象的value属性值为空字符串。
如某个表单元素没有name属性(即使有id属性),返回的数组中不会为此表单元素生成数组项。——因此Tony决定不研究、不使用它——Tony习惯使用id而不是name(Tony仅为radio使用name),Tony将实现自己的使用元素id的序列化方法。
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery object representing a set of form elements. The form elements can be of several types:

<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>

The .serializeArray() method uses the standard W3C rules for successful controls to determine which elements it should include; in particular the element cannot be disabled and must contain a name attribute. No submit button value is serialized since the form was not submitted using a button. Data from file select elements is not serialized.

This method can act on a jQuery object that has selected individual form elements, such as input, textarea, and select. However, it is typically easier to select the form tag itself for serialization:

$('form').submit(function() {
    console.log($(this).serializeArray());
    return false;
});

This produces the following data structure (provided that the browser supports console.log):

[
    {name:"a",value:"1"},
    {name:"b",value:"2"},
    {name:"c",value:"3"},
    {name:"d",value:"4"},
    {name:"e",value:"5"}
]

jQuery.com 上有 1 示例,未整理。

jQuery.param()

Returns: String
Description: Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.

version added: 1.2
jQuery.param(obj)
obj: An array or object to serialize.

version added: 1.4
jQuery.param(obj, traditional)
obj: An array or object to serialize.
traditional: A Boolean indicating whether to perform a traditional "shallow" serialization.

This function is used internally to convert form element values into a serialized string representation (See .serialize() for more information).

As of jQuery 1.3, the return value of a function is used instead of the function as a String.

As of jQuery 1.4, the $.param() method serializes deep objects recursively to accommodate modern scripting languages and frameworks such as PHP and Ruby on Rails. You can disable this functionality globally by setting jQuery.ajaxSettings.traditional = true;.

If the object passed is in an Array, it must be an array of objects in the format returned by .serializeArray():

[
    {name:"first",value:"Rick"},
    {name:"last",value:"Astley"},
    {name:"job",value:"Rock Star"}
]

Note: Because some frameworks have limited ability to parse serialized arrays, developers should exercise caution when passing an obj argument that contains objects or arrays nested within another array.

Note: Because there is no universally agreed-upon specification for param strings, it is not possible to encode complex data structures using this method in a manner that works ideally across all languages supporting such input. Until such time that there is, the $.param method will remain in its current form.

In jQuery 1.4, HTML5 input elements are also serialized.

We can display a query string representation of an object and a URI-decoded version of the same as follows:

示例一:

var myObject={
    a:{one:1,two:2,three:3},
    b:[1,2,3]
};
var recursiveEncoded = $.param(myObject);
var recursiveDecoded = decodeURIComponent(recursiveEncoded);
alert(recursiveEncoded);
alert(recursiveDecoded);

The values of recursiveEncoded and recursiveDecoded are alerted as follows:

a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3
a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3

To emulate the behavior of $.param() prior to jQuery 1.4, we can set the traditional argument to true:

示例二:
与上方 示例一 的 唯一区别是向 jQuery.param() 传递了第 2 个参数且参数值为 true。

The values of shallowEncoded and shallowDecoded are alerted as follows:

a=%5Bobject+Object%5D&b=1&b=2&b=3
a=[object+Object]&b=1&b=2&b=3

Example: Serialize a key/value object.

var aObject={height:100,width:100};
var aString=$.param(aObject);
alert(aString);//弹出height=100&width=100
alert($.param({height:"100px",width:"100px"}));//弹出height=100px&width=100px

Example: Serialize a few complex objects

//1.3.2及更早版本:
$.param({ a: [2,3,4] }) // "a=2&a=3&a=4"
//1.4及更新版本:
$.param({ a: [2,3,4] }) // "a[]=2&a[]=3&a[]=4"
//1.3.2及更早版本:
$.param({ a: { b:1,c:2 }, d: [3,4,{ e:5 }] }) // "a=[object+Object]&d=3&d=4&d=[object+Object]"
//1.4及更新版本:
$.param({ a: { b:1,c:2 }, d: [3,4,{ e:5 }] }) // "a[b]=1&a[c]=2&d[]=3&d[]=4&d[2][e]=5"