且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将javascript字典转换为编码的url字符串?

更新时间:2023-02-23 09:52:20

如果使用jQuery,您可以使用 jQuery.param

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