
jQuery param() method
The jQuery param()
method is used to create a serialized representation of an object, suitable for use in an HTTP request as URL parameters or in the request body. It takes an object as input and converts its key-value pairs into a query string format.
Here’s the basic syntax of the param()
method:
$.param(obj)
Parameters:
obj
: The JavaScript object to be serialized into a query string.
Example:
<!DOCTYPE html>
<html>
<head>
<title>jQuery param() Method Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="result"></div>
<script>
$(document).ready(function() {
// Data object to be serialized
var dataObj = {
name: "John",
age: 30,
city: "New York"
};
// Serialize the object into a query string
var queryString = $.param(dataObj);
// Display the serialized query string
$("#result").text("Serialized data: " + queryString);
});
</script>
</body>
</html>
In this example, we have a JavaScript object dataObj
with key-value pairs representing user information. We use the param()
method to serialize this object into a query string. The result will be a string containing the serialized data in the format "name=John&age=30&city=New%20York"
.
The param()
method is commonly used when making AJAX requests with data parameters. It helps in transforming data into a format that can be easily appended to the URL or included in the request body. It is particularly useful when working with APIs that expect URL-encoded parameters or when performing form submissions with AJAX.