[Javascript] Reading a variable from the URL

Terry Riegel riegel at clearimageonline.com
Tue Jul 17 17:07:16 CDT 2007


David,

This is a cool way of doing it. I am having trouble reading it though.

   var query_string = {};
   var query = window.location.search.substring(1);

I don't understand why this code produces the part of the URL after  
the ? mark. Can you please explain why it works? Also What does the  
{} mean?

Thanks,

Terry Riegel




On Jul 17, 2007, at 9:58 AM, David Dorward wrote:

>
> 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/
>
>
> _______________________________________________
> Javascript mailing list
> Javascript at LaTech.edu
> https://lists.LaTech.edu/mailman/listinfo/javascript
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.evolt.org/pipermail/javascript/attachments/20070717/7fa94f43/attachment.htm>


More information about the Javascript mailing list