go to  ForumEasy.com   
JavaPro  
 
 
   Home  |  MyForum  |  FAQ  |  Archive    You are not logged in. [Login] or [Register]  
Forum Home » JavaScript » Parse URL or Query String using JavaScript
Email To Friend  |   Set Alert To This Topic Rewarding Points Availabe: 0 (What's this) New Topic  |   Post Reply
Author Topic: Parse URL or Query String using JavaScript
WebSpider
member
offline   
 
posts: 147
joined: 06/29/2006
from: Seattle, WA
  posted on: 12/13/2006 03:45:32 PM    Edit  |   Quote  |   Report 
Parse URL or Query String using JavaScript
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>

 Profile | Reply Points Earned: 0

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