Wednesday, April 23, 2008

Get the querystring using JavaScript and Chaining

Okay, so this is going to be a very short pot... 'cause I don't have that much to say... except that everyday I use JavaScript, I like it more! Sure there are lots of drawbacks to it such as cross browser/os compatibility, and cross server insecurities... but you can do a lot to mitigate those issues, especially if you work with a good framework such as jQuery or YUI...

So what's the point of this whole post? Earlier today I created a js file that records metric information about website visitors... a pretty simple script... gather information such as screen resolution, user agent, color depth, ip address, session id, login id, etc and send it to a server side script to record the data.

So, one of the pieces I wanted to collect was the querystring. I wanted a clean one line solution to gathering that string.

I knew that window.location.href would give me the string version of the url currently in the browser so I thought I could split on the "?" resulting in "window.location.href.split('?')" Which in turn gave me an array containing 2 elements, the host string and the querystring... I am only interested in the query string... knowing that JS now treats the result as an array, I can grab the array element 1 (which is 2 in most programming languages...) like this: "window.location.href.split('?')[1]"... and there I have it!

No comments: