go to  ForumEasy.com   
JavaPro
Home » Archive » Message


[Email To Friend][View in Live Context][prev topic « prev post | next post » next topic]
  Parse URL or Query String using JavaScript
 
Subject: Parse URL or Query String using JavaScript
Author: WebSpider
Posted on: 12/13/2006 03:45:32 PM

Usually, parameters are passed to server and they are parsed on server side by ASP, JSP, and so on, since the web server needs to decide what to do next to dispatch the corresponding page back to client based on such specified parameters. For example, the protected pages should not be dispatched to unauthorized users.

For some scenarios, parameters must be parsed on client side embedded in JavaScript to interact with cookie. For example, the most common referral link

http://www.example.com/?id=referral_id

is going to pass the 'referral_id' to client and reside in client's computer with the aid of cookie for future use.

Here is the code as to how to get parameter info on client side.


<html>
<head>
<title>Javascript to parse url or querystring </title>
<script language="JavaScript">
<!--

/*
  name <cis>-- name of the desired variable 
  return string containing value <cs> of specified name <cis>
         or null if cookie name not exist
*/
function getValueFromUrl(name)
{
  var url = '' + this.location;
  var idx  = url.indexOf('?');
  if(idx==-1)
	return null;
  var query = "&" + url.substring(idx+1);
  var qs = query.toLowerCase();
  var key = "&" + name.toLowerCase() + "=";
  var begin = qs.indexOf(key);
  if(begin==-1)
	return null;
  else
    begin += key.length;
  var end = qs.indexOf("&", begin);
  if (end == -1)
    end = query.length;
  return unescape(query.substring(begin, end));
}
// -->
</script>

</head>
<body>
<script>
	document.write("URL is: "+this.location);
	document.write("<br>");
	document.write("Referral_id is: "+getValueFromUrl('id'));
</script>
</body>
</html>




References:

 


 
Powered by ForumEasy © 2002-2022, All Rights Reserved. | Privacy Policy | Terms of Use
 
Get your own forum today. It's easy and free.