jQuery ajax - param() method
example
Serialize a key/value Object:
var params = { width:1900, height:1200 }; var str = jQuery.param(params); $("#results").text(str);
Result:
width=1680&height=1050
TIY example
Output the result of serializing the object:
$("button").click(function(){ $("div").text($.param(personObj)); });
Definition and usage
The param() method creates a serialized representation of an array or object.
This serialized value can be used in the URL query string when making AJAX requests.
Syntax
jQuery.param(object,traditional)
Parameter | Description |
---|---|
object | The array or object to be serialized. |
traditional | Specify whether to use the traditional way of shallow serialization (parameter serialization). |
detailed description
The param() method is used to internally convert element values to a serialized string representation. See .serialize() Learn more information.
For jQuery 1.3, if the parameter passed is a function, then .param() will return the return value of the function, rather than returning the function as a string.
For jQuery 1.4, the .param() method will serialize the object recursively to meet the needs of modern scripting languages, such as PHP, Ruby on Rails, etc. You can globally disable this feature by setting jQuery.ajaxSettings.traditional = true;
If the object passed is in the array, it must be serialized with .serializeArray() the return value is an array of objects in the format:
[{name:"first",value:"Rick"}, {name:"last",value:"Astley"} {name:"job",value:"Rock Star"}]
Note:Because some frameworks have limited capabilities when parsing serialized numbers, be careful when passing arrays containing objects or nested arrays as parameters!
In jQuery 1.4, HTML5 input elements will also be serialized.
More examples
We can display the query string representation and URI encoded version of the object as follows:
var myObject = { a: { one: 1, two: 2, three: 3 }, b: [1,2,3] }; var recursiveEncoded = $.param(myObject); var recursiveDecoded = decodeURIComponent($.param(myObject)); alert(recursiveEncoded); alert(recursiveDecoded);
The values of recursiveEncoded and recursiveDecoded are output 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
You can set the traditional parameter to true to simulate the behavior of $.param() in versions before jQuery 1.4:
var myObject = { a: { one: 1, two: 2, three: 3 }, b: [1,2,3] }; var shallowEncoded = $.param(myObject, true); var shallowDecoded = decodeURIComponent(shallowEncoded); alert(shallowEncoded); alert(shallowDecoded);
The values of recursiveEncoded and recursiveDecoded are output as follows:
a=%5Bobject+Object%5D&b=1&b=2&b=3 a=[object+Object]&b=1&b=2&b=3