Rails allows the generation of query strings by passing a hash to a url_for type helper:
root_path({ :animals => {:dogs => ['pluto','spot'], :cats => 'garfiel开发者_JAVA百科d'} })
This will generate a url like:
http://example.com/?animals[dogs][]=pluto&animals[dogs][]=spot&animals[cats]=garfield
I want to use javascript to turn this into a JSON object so I have an object that matches the hash passed into the url helper in rails.
Using prototype.js I can call:
var params = window.location.search.toQueryParams();
params is a object but the original nested structure is not retained, instead I get:
{
"animals[dogs][]" : ["pluto","spot"],
"animals[cats]" : "garfield"
}
What I really want is:
{
"animals" : {
"dogs" : ["pluto","spot"],
"cats" : "garfield"
}
}
Also the reverse would be useful too. Prototype.js has toQueryString which in this case just returns an empty string:
Object.toQueryString({
"animals" : {
"dogs" : ["pluto","spot"],
"cats" : "garfield"
}
});
Is there a library of method that provides for this?
To answer my own question:
I found Ben Alman's jQuery BBQ which does it with a jQuery plugin.
http://benalman.com/code/projects/jquery-bbq/examples/deparam/?animals[dogs][]=pluto&animals[dogs][]=spot&animals[cats]=garfield
精彩评论