views:

1117

answers:

3

Is there any way to create the query parameters for doing a GET request in javascript. Just like in python you have urllib.urlencode() which takes in a dict (or list of two tuples) and creates a string like 'var1=value1&var2=value2'

+3  A: 

If you are using Prototype there is Form.serialize

If you are using jQuery there is Ajax/serialize

I do not know of any independent functions to accomplish this, though, but a google search for it turned up some promising options if you aren't currently using a library. If you're not, though, you really should because they are heaven.

Paolo Bergantino
A: 

This thread points to some code for escaping URLs in php. There's escape() and unescape() which will do most of the work, but the you need add a couple extra things.

function urlencode(str) {
str = escape(str);
str = str.replace('+', '%2B');
str = str.replace('%20', '+');
str = str.replace('*', '%2A');
str = str.replace('/', '%2F');
str = str.replace('@', '%40');
return str;
}

function urldecode(str) {
str = str.replace('+', ' ');
str = unescape(str);
return str;
}
Kibbee
encodeURIComponent handles this and doesn't incorrectly use + for a space.
AnthonyWJones
+10  A: 

Here you go:

// Usage:
//   var data = { 'first name': 'George', 'last name': 'Jetson', 'age': 110 };
//   var querystring = EncodeQueryData(data);
// 
function EncodeQueryData(data)
{
   var ret = [];
   for (var d in data)
      ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
   return ret.join("&");
}
Shog9
Exactly what I wanted, Thanks.
cnu
When iterating with `for`, use [hasOwnProperty](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty) to ensure interoperability.
troelskn
@troelskn, good point... although in this case, someone would have to be extending Object.prototype to break it, which is a pretty bad idea to start with.
Shog9