Often you need to do AJAX XHR calls, where you send information to a webserver to get information back. This snippet will extend Object with a method toParams() which will return a string ready for sending to a webserver.
1: Object.prototype.toParams=function () {
2: var sParams='';
3: for(a in this) {
4: var val=this[a];
5: if(typeof val!=='function') {
6: sParams+=((sParams!='')?'&':'')+a+'='+encodeURIComponent(val);
7: };
8: }
9: return sParams;
10: };
11:
12: // Example of use
13: var test={ 'a': 1,'b': 'hello værden' };
14: test.toParams();
15: // Return valud from test:
16: // a=1&b=hello%20v%C3%A6rden%20%3A-)
Tag: encodeURIComponent, toParams()