Skip to content

Instantly share code, notes, and snippets.

@whoahbot
Created June 28, 2012 17:17
Show Gist options
  • Save whoahbot/3012626 to your computer and use it in GitHub Desktop.
Save whoahbot/3012626 to your computer and use it in GitHub Desktop.
Change for serializing arrays to query params in MooTools.
Object.toQueryString({'buh':[1,2]});
"buh[0]=1&buh[1]=2"
On the server side, it looks like:
buh = {0 => 1, 1 => 2}
And we have to do buh.values in order to get it to return an array.
With this patch the query string becomes:
Object.toQueryString({'buh':[1,2]});
"buh[]=1&buh[]=2"
And on the server-side, it's serialized into an array.
// Changes the toQueryString behavior so that arrays aren't converted
// to hashes server-side.
toQueryString: function(object, base){
var queryString = [];
Object.each(object, function(value, key){
if (base) key = base + '[' + key + ']';
var result;
switch (typeOf(value)){
case 'object': result = Object.toQueryString(value, key); break;
case 'array':
var vals = value.map(function(val){
return key + "[]=" + val;
});
result = vals.join(',');
break;
default: result = key + '=' + encodeURIComponent(value);
}
if (value != null) queryString.push(result);
});
return queryString.join('&');
}
@3n
Copy link

3n commented Jun 29, 2012

From what I can see online, "buh[]=1&buh[]=2" isn't exactly "the" standardized way of sending arrays via query strings, but it's as close as people get (PHP understands it natively). If that's what works for you guys, then we might as well stick with it.

However, this would be a super-duper breaking change in MooTools Core, so there's roughly a 0% chance of them including the patch. I'd just monkey-patch toQueryString on Object to do what you want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment