Counterpart to getURLVars() for simplifying vars

1k views Asked by At

I am using this function to scrape my url and build variables from it:

Read a page's GET URL variables and return them as an "associative array." Calling the function while at example.html?foo=asdf&bar=jkls sets map['foo']='asdf' and map['bar']='jkls'

how would I add a for loop so that

foo = map['foo']
bar = map['bar']

?

First solution didn't work.

2

There are 2 answers

4
David Ruttka On BEST ANSWER

You can loop through the map like this

for (var key in map)
{
    window[key] = map[key];
}

This would create window[foo] and window[bar], which are the same as window.foo and window.bar, which are the same as foo and bar.

EDIT: Here are the contents of the body in the test page I'm using. jQuery should be loaded in the head only because I use it to initialize my test and attach a click handler, but the concept of the for loop is not dependent on jQuery. Since I don't have the map coming into me, I am creating it myself when the document loads. From that point, I am looping over the map just as I described and attaching a click handler to a button to test the proper assignment.

    <input type="button" />

    <script type="text/javascript" language="javascript">
        $(document).ready(function(){
            /* You don't need to build the map, you should already have it
            var map = new Object();
            map.foo='bar';
            map.test='meh';
            */

            // This is the loop from my original post
            for (var key in map)
            {
                window[key] = map[key];
            }

            // This is just a debug handler, you wouldn't need it
            $('input[type="button"]').click(function(){
                // This is very annoying, but proves that all three methods of access are valid for both variables
                alert(window['foo']);
                alert(window.foo);
                alert(foo);
                alert(window['test']);
                alert(window.test);
                alert(test);
                return false;
            });
        });
    </script>

1
Martijn On

Why would you want to clobber the global namespace with all those variables? What is wrong with using map.foo and map.bar? — You do know that map['foo'] and map.foo are exactly the same?

Besides, what you want is very unsecure. If someone opened your page with URL query parameters ?%24=test you’d be screwed: jQuery wouldn’t work anymore since you’d have overwritten the $ global variable.

Also, keep in mind that URL parameters are normally not case-sensitive, but Javascript is. So, usually ?KEY=value will be the same as ?key=value. map.key and map.KEY, however are treated as different variables.