开发者

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

开发者 https://www.devze.com 2023-03-27 14:53 出处:网络
Closed. This question needs details or clarity. It is not currently accepting answers. Want to improve this question? Add details and clarify 开发者_JS百科the problem by editing this post.
Closed. This question needs details or clarity. It is not currently accepting answers.

Want to improve this question? Add details and clarify 开发者_JS百科the problem by editing this post.

Closed 3 years ago.

Improve this question

I'd like to get something like

?key=value?key=value

out of a js dictionary that is

{
    key:value,
    key:value
}


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"}));


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


The same in ECMAScript 2016:

let params = { width:1680, height:1050 };
// convert object to list -- to enable .map
let data = Object.entries(params);
// encode every parameter (unpack list into 2 variables)
data = data.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
// combine into string
let query = data.join('&');
console.log(query); // => width=1680&height=1050

Or, as single-liner:

let params = { width:1680, height:1050 };
Object.entries(params).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
// => "width=1680&height=1050"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号