[Javascript] Reading a variable from the URL

David Dorward david at dorward.me.uk
Tue Jul 17 08:58:53 CDT 2007


On 17 Jul 2007, at 14:25, Terry Riegel wrote:
> I am working on a simple slideshow. The page will be static with  
> javascript added for interactivity. I would like to read the URL do  
> determine what image is the current image. For example the static  
> page is.
>
> /sites/thebrowns/photos/200707/id200707030607.html
>
> It could be called like this...
>
> /sites/thebrowns/photos/200707/id200707030607.html?image=5
>
> Since it is static I would like my javascript to parse the URL and  
> set image to 5.

I wrote this a while ago, one say I'll get round to finishing it off,  
but its functional now. You'll end up with an object representing all  
the values in the query string.

var QueryString = function () {
   // This function is anonymous, is executed immediately and
   // the return value is assigned to QueryString!
   var query_string = {};
   var query = window.location.search.substring(1);
   var vars = query.split("&");
   for (var i=0;i<vars.length;i++) {
     var pair = vars[i].split("=");
		// If first entry with this name
     if (typeof query_string[pair[0]] === "undefined") {
       query_string[pair[0]] = pair[1];
		// If second entry with this name
     } else if (typeof query_string[pair[0]] === "string") {
       var arr = [ query_string[pair[0]], pair[1] ];
       query_string[pair[0]] = arr;
		// If third or later entry with this name
     } else {
       query_string[pair[0]].push(pair[1]);
     }
   }
	return query_string;
} ();


-- 
David Dorward
http://dorward.me.uk/
http://blog.dorward.me.uk/





More information about the Javascript mailing list