Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement something like PHP's http_build_query and the reverse in javascript?

Tags:

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 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

like image 864
wamp Avatar asked Jun 03 '10 02:06

wamp


1 Answers

Nowadays, you can simply use the URLSearchParams constructor on your object.

const data = {
  "test1": 1,
  "test2": "two",
  "test3": 3,
};

const params = new URLSearchParams(data);

console.log(params.toString());
like image 138
xinthose Avatar answered Sep 27 '22 22:09

xinthose