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
2008-09-21 17:49:10
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
2008-09-21 17:50:17
encodeURIComponent handles this and doesn't incorrectly use + for a space.
AnthonyWJones
2008-09-21 19:45:31
+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
2008-09-21 17:53:45
When iterating with `for`, use [hasOwnProperty](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty) to ensure interoperability.
troelskn
2008-09-21 19:29:44
@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
2008-09-21 19:57:19