Do you know a fast and simple way to encode a javascript object into a string that I can pass via GET?
No jQuery, no other frameworks, just plain Javascript :)
Do you know a fast and simple way to encode a javascript object into a string that I can pass via GET?
No jQuery, no other frameworks, just plain Javascript :)
like this?
serialize = function(obj) {
var str = [];
for(var p in obj)
str.push(p + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
alert(serialize({foo: "hi there", bar: "100%" }));
// edit: this one also converts recursive objects (using php "array" notation for the query string)
serialize = function(obj, prefix) {
var str = [];
for(var p in obj) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push(typeof v == "object" ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
return str.join("&");
}
alert(serialize({foo: "hi there", bar: { blah: 123, quux: [1, 2, 3] }}));
Do you need to send arbitrary objects? If so, GET is a bad idea since there are limits to the lengths of URLs that user agents and web servers will accepts. My suggestion would be to build up an array of name-value pairs to send and then build up a query string:
function QueryStringBuilder() {
var nameValues = [];
this.add = function(name, value) {
nameValues.push( {name: name, value: value} );
};
this.toQueryString = function() {
var segments = [], nameValue;
for (var i = 0, len = nameValues.length; i < len; i++) {
nameValue = nameValues[i];
segments[i] = encodeURIComponent(nameValue.name) + "=" + encodeURIComponent(nameValue.value);
}
return segments.join("&");
};
}
var qsb = new QueryStringBuilder();
qsb.add("veg", "cabbage");
qsb.add("vegCount", "5");
alert( qsb.toQueryString() );
use JSON.
take a look at this question for ideas on how to implement.