0

Possible Duplicate:
querystring encoding of a javascript object

I'm trying to make a request to a website and embed the result as an iframe in the page using javascript. I need to pass a number of parameters in the request as querystring variables and I'd like to be able to specify the parameters as an object, passing them to a function to produce a querystring so they are easy to read, maintain and manipulate.

How can I construct the querystring of a URL from a JSON object with simple values? I would expect this example:

{
    h:300,
    w:300,
    skip:500,
    count:50
}

to produce the following querystring:

h=300&w=300&skip=500&count=50

Are there any existing library functions to do this, or is the best thing to loop over the properties myself?

Community
  • 1
  • 1
Paul Turner
  • 37,274
  • 14
  • 96
  • 161

2 Answers2

4

jQuery has a built-in method for this: jQuery.param()

oleq
  • 17,373
  • 2
  • 35
  • 64
0

I recommend you use jQuery's param(). Here is the documentation http://api.jquery.com/jQuery.param/

You would pass your object like so:

var myObj = { h:300, w:300, skip:500, count:50 }

console.log('=>', $.param(myObj) ); // prints => h=300&w=300&skip=500&count=50

Sam3k
  • 940
  • 1
  • 11
  • 22