Url Encode javascript object literal Url Encode javascript object literal ajax ajax

Url Encode javascript object literal


You should use jQuery.param:

$.param({foo:'bar', fizz:'buzz'});//produces foo=bar&fizz=buzz

Arrays are ok too:

$.param({foo:['bar', 'baz']});//produces foo%5B%5D=bar&foo%5B%5D=baz//which is the url encoded form of: foo[]=bar&foo[]=baz

if you need the traditional array syntax, use the second parameter:

$.param({foo:['bar','baz']}, true);//produces foo=bar&foo=baz


To escape a single value, Javascript has the function escape. You must provide your own function to iterate through the object, add the keys, and so on.

EDIT

Esailija is kind enough to remind me that escape does not handle many common cases properly, and encodeURIComponent is much better. If you're already using jQuery (and you should be), zzzzBov's answer is better still.