tags:

views:

628

answers:

4

How to get "GET" variables from request in JavaScript?

Does jQuery ou YUI! has this feature built-in?

+1  A: 

You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href.

Thomas Owens
Note that this isn't entirely reliable, as the server may have redirected you elsewhere. But it's the best you can do.
Joel Coehoorn
+3  A: 

You can use the URL to acquire the GET variables. In particular, window.location.search gives everything after (and including) the '?'. You can read more about window.location here.

Daniel Lew
+4  A: 

All data is available under

window.location.search

you have to parse the string, eg.

function get(name){
   if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
      return decodeURIComponent(name[1]);
}

just call the function with GET variable name as parameter, eg.

get('foo');

this function will return the variables value or undefined if variable has no value or doesn't exist

Rafael
This code shouldn't url decode?
Daniel Silveira
@Daniel Silveira: yes, it could/should decode the value (and encode the name). Will edit my post in few moments
Rafael
Isn't better to just give only one code snippet?
Daniel Silveira
yes, you're right. Sorry.
Rafael
Note that decodeURIComponent does not decode /all/ possible URI escapes. In particular "+" won't be decoded as " ". (I forget which browser this was in. FF, maybe?) The spec requires them to only decode exactly what encodeUIRComponent encodes, and it will encode " " as "%20", so "+" is left alone.
Jesse Rusak
+2  A: 

If you already use jquery there is a jquery plugin that handles this:

http://plugins.jquery.com/project/query-object

brendan