PDA

View Full Version : Ext.urlEncode with nested objects/arrays support



bcd
13 Dec 2009, 12:25 AM
I've made a new urlEncode function which can handle nested objects

Example:


{
a:{
b: [1,2,3,4],
c: 5
},
d:{
e: {
f:6
}
},
g:7,
h:[8,9,10]
}
will encode to: a[b][]=1&a[b][]=2&a[b][]=3&a[b][]=4&a[c]=5&d[e][f]=6&g=7&h[]=8&h[]=9&h[]=10


The code:

Ext.urlEncode = function(o, pre, parentKey){
var buf = [];
if(Ext.type(o)=='array'){
for(i=0;i<o.length;i++) {
val = o[i];
if(Ext.type(val)=='array' || Ext.type(val)=='object') {
buf = buf.concat(Ext.urlEncode(val, '', (Ext.isDefined(parentKey) ? parentKey : "")+'[]'));
} else {
buf[buf.length] = {key:(Ext.isDefined(parentKey) ? parentKey+'[]' : i.toString()), value:val};
}
}
}
if(Ext.type(o)=='object'){
for(key in o) {
val = o[key];
if(Ext.type(val)=='array' || Ext.type(val)=='object') {
buf = buf.concat(Ext.urlEncode(val, '', (Ext.isDefined(parentKey) ? parentKey+'['+key+']' : key)));
} else {
buf[buf.length] = {key:(Ext.isDefined(parentKey) ? parentKey+'['+key+']' : key), value:val};
}
}
}
if(Ext.isDefined(parentKey)) {
return buf;
} else {
return (Ext.isEmpty(pre)?"":pre+"&") + buf.map(function(x){return (x.key)+'='+encodeURIComponent(x.value.toString());}).join('&');
}
};

vahid4134
13 Dec 2009, 11:43 PM
I wrote this
http://www.extjs.com/forum/showthread.php?t=85170
but forum moderator move my Thread to help. I dont know why!!!

davitz38
14 Dec 2009, 1:56 AM
Hi guys,
I use this url encoder online tool (http://www.stringfunction.com/url-encode.html) to make sure I'm encoding the right way
David

vahid4134
14 Dec 2009, 4:57 AM
This method change array or object to url

mystix
14 Dec 2009, 6:05 AM
I wrote this
http://www.extjs.com/forum/showthread.php?t=85170
but forum moderator move my Thread to help. I dont know why!!!

i moved it back from Help from Extensions.

i thought it was a question. my bad.