Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn a javascript dictionary into an encoded url string? [closed]

Tags:

javascript

I'd like to get something like

?key=value?key=value

out of a js dictionary that is

{
    key:value,
    key:value
}
like image 625
ocoutts Avatar asked Aug 12 '11 19:08

ocoutts


2 Answers

If using jQuery, you can use jQuery.param:

var params = { width:1680, height:1050 };
var str = jQuery.param( params );
// str is now 'width=1680&height=1050'

Otherwise, here is a function that does it:

function serialize(obj) {
  var str = [];
  for(var p in obj)
     str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
  return str.join("&");
}
alert(serialize({test: 12, foo: "bar"}));
like image 147
Alex Turpin Avatar answered Nov 07 '22 23:11

Alex Turpin


There is a much simpler way to do this now:

API for URLSearchParams is here

var url = new URL('https://example.com/');
url.search = new URLSearchParams({blah: 'lalala', rawr: 'arwrar'}); 
console.log(url.toString()); // https://example.com/?blah=lalala&rawr=arwrar
like image 20
jfunk Avatar answered Nov 07 '22 21:11

jfunk