PDA

View Full Version : retrieving variables from URL in javascript


gibby
09-22-2005, 12:44 AM
Hello,

Say I've got a test page that I open with the following URL:

http://localhost/test.html?name=Clark

And on the page I've got this javascript code:

<!DOCTYPE HTML "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
function sayhello(name)
{
document.write('hello ' + name + '!');
return;
}
</script>
</head>
<body>
<script language="javascript">
sayhello(name);
</script>
</body>
</html>

But when I run this page with the URL above, I get

hello !

That is, the value of name (Clark) does not show up.

I thought that in Javascript, referencing variables was as simple as using their names, so if you had a variable with a value in the URL, you could use it in your javascript code just as you would if you declared it locally. Is this wrong? Is there a different way of doing it?

You can see this page by type the following URL in the address bar:

http://www.shahspace.com/test.html?name=[yourname]

Thanks for your help.

maskd
09-22-2005, 01:18 AM
I don't really see it as practical, but it can be done, but it's not as simple as you think.

A simply worded Google Search (http://www.google.com.au/search?q=javascript+url+variables&start=0&start=0&ie=utf-8&oe=utf-8&client=firefox-a&rls=org.mozilla:en-US:official) brought up a few answers, this being the first one:


<script language="JavaScript">
<!--
// Create variable is_input to see if there is a ? in the url
var is_input = document.URL.indexOf('?');

// Check the position of the ? in the url
if (is_input != -1)
{
// Create variable from ? in the url to the end of the string
addr_str = document.URL.substring(is_input+1, document.URL.length);

// Loop through the url and write out values found
// or a line break to seperate values by the &
for (count = 0; count < addr_str.length; count++)
{

if (addr_str.charAt(count) == "&")
// Write a line break for each & found
{document.write ("<br>");}

else
// Write the part of the url
{document.write (addr_str.charAt(count));}

}}

// If there is no ? in the url state no values found
else
{document.write("No values detected");}

-->
</script>