Snippet: Javascript – Extend Object with toParams()

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 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+'='+(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-)
US

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>