Welcome to WebmasterWorld Guest from 54.234.63.187

Forum Moderators: open

Message Too Old, No Replies

JavaScript to read a URL query string?

Can this be done client side?

     

dhdweb

12:33 am on Oct 28, 2002 (gmt 0)

10+ Year Member



Is there a way for JS to get the var of a URL query string?
If so, can it be done locally?

I need to duplicate a PHP function in JS to change a pages display based on the value of a var, and it has to be done client side on a local drive.

The string would be simple like: page.htm?a=1
I need to get the value of "a"

Any ideas?

dhdweb

tedster

1:21 am on Oct 28, 2002 (gmt 0)

WebmasterWorld Senior Member tedster is a WebmasterWorld Top Contributor of All Time 10+ Year Member



For http://example.com/page.html?a=xxx, the two lines below should return the value after the "=" for the variable "xxx":

fullURL = parent.document.URL
xxx = fullURL.substring(fullURL.indexOf('?')+3, fullURL.length)

It says to "Take the text string of the URL. Use a substring beginning three past the position of the "?" and going through the end of the text string.

starway

7:02 am on Oct 28, 2002 (gmt 0)

10+ Year Member



You can also use document.location.search to extract the query substring.
Then, if you pass several vars with values, you can use split() javascript method: it will create an erray composed from vars/values separated by a separator, which is "=" in our case.

dhdweb

10:48 pm on Oct 28, 2002 (gmt 0)

10+ Year Member



Ok, I got a script put together that gets the vars from the query string. :):)

The only problem now is that if I send a=01, the result is a=1 :(
How do I preserve the zero before the one? I need the output to be a=01

dhdweb

dhdweb

12:06 am on Oct 29, 2002 (gmt 0)

10+ Year Member



Better yet, can anyone solve this problem?

Using the following script:


function getArgs() {
var args = new Object();
var query = location.search.substring(1);
var pairs = query.split("&");
for(var i = 0; i < pairs.length; i++) {
var pos = pairs[i].indexOf('=');
if (pos == -1) continue;
var argname = pairs[i].substring(0,pos);
var value = pairs[i].substring(pos+1);
args[argname] = unescape(value);
}
return args;
}
var args = getArgs();
if (args.a) a = parseInt(args.a);
document.write(a);

If the query is "?a=01" thru "?a=07" the output is 1 thru 7
But, (this is the killer!)
If the query is "?a=08" or "?a=09" the output is 0

Please help!

dhdweb

dhdweb

1:10 am on Oct 29, 2002 (gmt 0)

10+ Year Member



Ok, I changed

if (args.a) a = parseInt(args.a);

to

if (args.a) a = parseFloat(args.a);

and now it works fine! :o

dhdweb

 

Featured Threads

Hot Threads This Week

Hot Threads This Month