您知道一种快速而简单的方法将Javascript对象编码成我可以通过GET
请求传递的string
吗?
没有jQuery
,没有其他框架--只是简单的Javascript :)
发布于 2009-11-11 20:31:26
是像这样吗?
serialize = function(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
console.log(serialize({
foo: "hi there",
bar: "100%"
}));
// foo=hi%20there&bar=100%25
Edit:它还可以转换递归对象(使用php "array“表示法作为查询字符串)
serialize = function(obj, prefix) {
var str = [],
p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push((v !== null && typeof v === "object") ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
console.log(serialize({
foo: "hi there",
bar: {
blah: 123,
quux: [1, 2, 3]
}
}));
// foo=hi%20there&bar%5Bblah%5D=123&bar%5Bquux%5D%5B0%5D=1&bar%5Bquux%5D%5B1%5D=2&bar%5Bquux%5D%5B2%5D=3
发布于 2018-11-06 19:57:26
只需使用URLSearchParams
此works in all current browsers
new URLSearchParams(object).toString()
发布于 2011-12-15 20:43:55
jQuery有一个这样的函数,jQuery.param()
,如果你已经在使用它,你可以使用它:http://api.jquery.com/jquery.param/
示例:
var params = { width:1680, height:1050 };
var str = jQuery.param( params );
str
现在包含width=1680&height=1050
https://stackoverflow.com/questions/1714786
复制相似问题