JQuery : create URL query string from JSON/Array

2 min read
Share:

Hi Friends,

I was writing javascript to reload my page with different parameters. So I needed to create the queryString of those parameters but I didn’t want to create it of my own. I already knew about jQuery.serialize() which serializes the form and creates the queryString, but unfortunately I didn’t have form. So that gave me opportunity to learn about new jQuery.param() which converts the JSON/Array into query string. Let us look at few examples below :

[js]
var myParams = {country:"US", customerId:"1"}
jQuery.param(myParams);

Output: "country=US&customerId=1"
[/js]

 

[js]
var myParams = {name: "Amit Jain",days:[‘Mon’,’Tue’,’Sat’] };
jQuery.param(myParams);

Output: "name=Amit+Jain&days%5B%5D=Mon&days%5B%5D=Tue&days%5B%5D=Sat"
[/js]

 

[js]
var myParams = {name: "Diana",address:{
line1:"232 Alder Dr.",
line2:"Alder City",
state : "Utah",
country: "US"
}};
jQuery.param(myParams);

Output : "name=Diana&address%5Bline1%5D=232+Alder+Dr.&address%5Bline2%5D=Alder+City&address%5Bstate%5D=Utah&address%5Bcountry%5D=US"
[/js]

Hope this helped!

Contact our Grails developers team for your queries.

Cheers!

comments ( 4 )

    1. Amit Jain profile picture

      After a quick search it looks like, there is no method provided by jQuery as such, people have given there own custom solutions for the same.

      Reply ↓
  1. Vivek Krishna profile picture

    Hi,

    To add on, from jQuery 1.4 simply writing $.param() doesn’t create the query string, the way we want it. It adds “[]” to arrays. For example, customers:[{name:”Amit”}, {name:”Vivek”}] gets serialized with the name customers[] in the params instead of simply being customers.

    This can be taken care of, by:

    $.param(, true), where true is for the “traditional” way of parameterizing the data.

    This can be set to default at the global level by setting

    jQuery.ajaxSettings.traditional = true;

    globally. 🙂

    Reply ↓

Leave a Reply

Your email address will not be published. Required fields are marked *