Tuesday, 14 May 2013

Convert Object to QueryString in Sencha Touch 2

In Sencha Touch 2, today i came across a handy function Ext.Object.toQueryString() which is used to convert object into encoded query string. This encoded query string can be appended to URL which can used for Store Proxy URL configuration in order to fetch JSON/XML data  from remote server. Let me explain with an example

Example1:
var object1 = {fname:'suresh',lname:'kumar'};
var queryStr = Ext.Object.toQueryString(object1);
output: fname=suresh&lname=kumar

Example2:
var object2 = {fname:'suresh',lname:'kumar',hobbies:['reading books','writing blogs', 'playing games']};
var queryStr = Ext.Object.toQueryString(object2);
output: fname=suresh&lname=kumar&hobbies=reading%20books&hobbies=writing%20blogs&hobbies=playing%20games

This function will also supports the recursive objects conversion, let's see the implementation.

Example3:
var object3 = {
  fname:'suresh',
  lname:'kumar',
  hobbies:['reading books','writing blogs', 'playing games'],
  dateOfBirth: {
    day: 29,
    month: 8,
    year: 1983
  }
};

var queryStr = Ext.Object.toQueryString(object3,true);
output: fname=suresh&lname=kumar&hobbies=reading%20books&hobbies=writing%20blogs&hobbies=playing%20games&dateOfBirth[day]=29&dateOfBirth[month]=8&dateOfBirth[year]=1983

For recursive objects, we need to pass second parameter as true. By default it is false.

Hope, you enjoyed this Post.

No comments:

Post a Comment