Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

No jQuery, no other frameworks - just plain Javascript :)

like image 535
napolux Avatar asked Nov 11 '09 12:11

napolux


People also ask

What is Querystring in JavaScript?

A query string is part of the full query, or URL, which allows us to send information using parameters as key-value pairs.

What is URLSearchParams?

The URLSearchParams interface defines utility methods to work with the query string of a URL.


1 Answers

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)

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
like image 94
11 revs, 9 users 35% Avatar answered Nov 10 '22 08:11

11 revs, 9 users 35%