Client Side GET Vars
For this week's Script Sunday, I wrote a quick tool that provides GET vars in an easily accessible object.
But first, a disclaimer:
-
GETvars certainly have their place in the world of the web, but I don't necessarily condone them. There are better ways. In my personal projects and in the workplace, I used pretty URLs and haven't looked back since. They're cleaner, easier to understand, and have far better SEO value. -
Accessing
GETvars on the client-side is odd, and shouldn't be necessary. That said, I still think it's neat that you can.
Now that we've got that out of the way, here's the script:
The script parses location.href, getting everything after the ?. It then creates key/value pairs based on the GET values and returns them.
Easy! Some quick notes: if a key is not set to a value, the default is true (see example 2 if this confuses you).
Also, like most other interfaces for this, if a variable is repeated, then the last value is the one that's kept.
As usual, you can try this out right here. I've provided some links that toss some meaningless GET vars into the mix. Click away and try it out!
- Example 1 - lots of vars
- Example 2 - variable without value
- Example 3 - repeat var
- Example 4 - everything!
- [Download get-vars.js] (543 bytes)
- [Download get-vars-min.js] (221 bytes; compressed)
Neat! Thanks.
obj = window.location.search.parseQuery();
This seems to do much the same thing?
@daniel: Looks like you’re using the Prototype JS library, which extends String with a parseQuery method: http://www.prototypejs.org/assets/2008/1/25/prototype-1.6.0.2.js
That would explain it. Thanks for pointing that out :)