Rails allows the generation of query strings by passing a hash to a url_for type helper:
root_path({ :animals => {:dogs => ['pluto','spot'], :cats => 'garfield'} })
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.