Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

javascript - Javascript对象的查询字符串编码(Query-string encoding of a Javascript Object)

Do you know a fast and simple way to encode a Javascript Object into a string that I can pass via a GET Request?(您是否知道将Javascript对象编码为可通过GET请求传递的string的快速简便的方法?)

No jQuery , no other frameworks - just plain Javascript :)(没有jQuery ,没有其他框架-仅是纯Javascript :))

  ask by Napolux translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

like this?(像这样?)

 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: this one also converts recursive objects (using php "array" notation for the query string)(编辑:这也转换递归对象(使用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 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...