Original: http://jquery-howto.blogspot.jp/2009/09/get-url-parameters-values-with-jquery.html
In this post, I would like to share a little JQuery code snippet that makes getting URL parameters and their values mo Re convenient.
Recently, while working in one of my projects, I needed to read and get parameter values from URL string of the current PA GE that is constructed and sent by PHP script. I came across this short and sweet JavaScript code snippet to Roshambo that does just.
Read a page ' s GET URL variables and return them as an associative array.
functionGeturlvars()
{
VarVARs= [],Hash;
VarHashes=Window.Location.Href.Slice(Window.Location.Href.IndexOf(‘?‘) + 1).Split(' & ');
For(VarI= 0;I<Hashes.Length;I++)
{
Hash=Hashes[Isplit ( ' = ' Vars. Pushhash[0
Vars[hash[0]] = Hash [1
}
Return Vars; } /span>
The function returns a array/object with your URL parameters and their values. For example, consider we have the following URL:
http://www.example.com/?me=myValue&name2=SomeOtherValue
Calling getUrlVars()
function would return you the following array:
{
"me" : "myValue",
"name2" : "SomeOtherValue"
}
To get a value of first parameter you would does this:
var first = getUrlVars()["me"];
// To get the second parameter
var second = getUrlVars()["name2"];
The script syntax to look more jquery like syntax I rewrote it as a extension for jQuery:
$.Extend({
Geturlvars: function(){
VarVARs= [],Hash;
VarHashes=Window.Location.Href.Slice(Window.Location.Href.IndexOf(‘?‘) + 1).Split(' & ');
For(VarI= 0;I<Hashes.Length;I++)
{
Hash=Hashes[I].Split(=);
VARs.Push(Hash[0]);
VARs[Hash[0]] = Hash[1
}
Return Vars; },
Geturlvar: function (name
return $. () [name];
}
});
Now, if you include the "above code in your" JavaScript file, you can get URL parameter values in the following-in-a-do:
// Get object of URL parameters
var allVars = $.getUrlVars();
// Getting URL var by its nam
var byName = $.getUrlVar(‘name‘);
Get URL Parameters & values with JQuery