views:

598

answers:

3

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 :)

+5  A: 

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] }}));
stereofrog
Napolux
note `p` should be encodeURIComponent-ed too
bobince
Won't it break given {foo: [1,2,3], bar: "100%" } ?
David Dorward
If the values in your associative array can be arrays/objects themselves, then this won't work (because encodeURIComponent is expecting a string - i hope it works with numbers...). You have to somehow represent the fact that this value has "sub-values" and so on. smart people have already thought about this problem and came up with JSON, so making up your own representation is reinventing the wheel. that's why I think in general my answer is better (although it may be that in your specific case this answer is good enough).
Ofri Raviv
@Ofri: For POST requests to a server set up to receive it, JSON is a good choice. For GET requests, if you're sending anything other than a few simple parameters to the server then it's likely your design is wrong.
Tim Down
A: 

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() );
Tim Down
+2  A: 

use JSON.

take a look at this question for ideas on how to implement.

Ofri Raviv
i'm wondering how he's expected to talk JSON with a server that probably won't understand it
stereofrog
I don't know what he's writing the server in, but most modern languages have good packages that read JSON. Besides, even if he ends up implementing it, its better to implement a JSON-reading server code than to invent a new encoding scheme of your own. DIY encodings like this tend to be buggy (because you usually don't think of all the possible cases, like the value being an array in itself etc').
Ofri Raviv