Javascript对象的查询字符串编码 [英] Query-string encoding of a Javascript Object
本文介绍了Javascript对象的查询字符串编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您是否知道将Javascript对象编码为字符串
的快速而简单的方法,我可以通过 GET $ c $传递c>请求?
Do you know a fast and simple way to encode a Javascript Object into a string
that I can pass via a GET
Request?
否 jQuery
,没有其他框架 - 只是简单的Javascript:)
No jQuery
, no other frameworks - just plain Javascript :)
推荐答案
是这样的?
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
编辑:这个也转换递归对象(使用php数组查询字符串的表示法
this one also converts recursive objects (using php "array" notation for the query string)
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
这篇关于Javascript对象的查询字符串编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文