views:

77

answers:

2
<?php
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data);
/* Output:
      foo=bar&baz=boom&cow=milk&php=hypertext+processor
*/

How to do similar thing in javascript,say, get the query string from the array ,and convert the array to query string?

UPDATE

the jquery plugin is not working:

var fromVar = $.query.load('?cow=milk')
fromVar.set('first', 'value'); 
fromVar.toString()

It outputs ?cow=milk while I want it to be ?cow=milk&first=value

A: 

Try the jQuery query plugin. It's pretty intuitive. You can use get and set accessors to read and modify the query string:

var cow = $.query.get('cow');
$.query.set('cow', 'goat');

You can create a new query object from an existing string:

var fromVar = $.query.load('?cow=milk')
var cow = fromVar.get('cow'); // milk

You can also create an empty object:

var newQ = $.query.empty();
newQ = newQ.set('first', 'value'); // "?first=value"
Matthew Flaschen
No, I don't want it to get query string from location.href, but from a specific javascript variable.
wamp
You can create it from an existing string.
Matthew Flaschen
This plugin is not working.
wamp
There was a bug above, which I fixed. I made a demo at http://jsfiddle.net/jwCpg/ .
Matthew Flaschen
A: 

If you're using jQuery, then you can use the jQuery.param() function:

var array = { "foo":"bar", "baz":"boom", "php":"hypertext processor" };
var str = jQuery.param(array);
alert(str); // should be "foo=bar&baz=boom&php=hypertext+processor"

It can serialise some complex arrays too.

Les