PDA

View Full Version : get URL value



DJWiktor
Sep 5th, 2003, 11:01 AM
//Trivial question, but I keep having problems with this in JS.
//I need to get the value of one variable from my URL

http://www.mysite.com?myvar=2

//here's how I try to do it, without success

document.write("variable="+window.document.location.award.value);

//any help would be appreciated

//wiktor

liorean
Sep 5th, 2003, 11:14 AM
Hmm, you will have to read document.location.search, then strip out the question mark, the variable name, and the quotation mark.

DJWiktor
Sep 5th, 2003, 11:20 AM
Well, isn't there an easier way?

in ASP i simply use - request.querystring("myvar")
in PHP even simpler - $myvar

what about JavaScript?
isn't there an easier method?

wiktor

liorean
Sep 5th, 2003, 01:21 PM
Frankly, no. But it's easy to do it nontheless:

function fnGetURLQuery(){
var
sURLQuery=document.location.search.slice(1),
aURLQuery=sURLQuery.split(/[&;]/), // Separate the variables
re=/(.*)=(.*)/, // For capturing the name-value pairs
i=aURLQuery.length, // Iterator over the variables
oURLQuery={}, // Your results object
aTemp; // Temporary array
while(i-->0){ // For each variable
aTemp=re.exec(aURLQuery[i]); // Capture the name-value pairs
oURLQuery[aTemp[1]]=unescape(aTemp[2]); // And store them in the results object
}
return oURLQuery; // Return the restults object
}
Then, the return from fnGetURLQuery will be an object, which in turn will have all the variables in the query string as members.

Thus:
var
oQuery=fnGetURLQuery(); // Store the query
alert(oQuery['myvar']); // Alert the contents of the myvar query variable

DJWiktor
Sep 8th, 2003, 09:22 AM
great, works perfect except for a little change in line

oQuery=fnGetURLQuery() {}; // Store the query

should be

oQuery=fnGetURLQuery(); {} // Store the query

thanx a lot. it solves many of my problems.

wiktor

liorean
Sep 8th, 2003, 11:05 AM
Hmmm nope. The {} shouldn't be there at all. My bad, it's corrected now.