How to implement something like PHP http_build_query and vice versa in javascript?

<?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 a similar thing in javascript, say get a query string from an array and convert array in the query string ?

UPDATE

jquery plugin does not work:

 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

+7
javascript
source share
2 answers

If you are using jQuery, you can use the jQuery.param () function:

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

It can also serialize some complex arrays.

+24
source

Try the jQuery query plugin . This is 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 line:

 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" 
-2
source

All Articles