JScript parameters

Ever wondered how to get rid of those pesky *.js.php files where you need PHP to write a single variable into a JScript?

After a lot of searching I stumbled upon a nice solution (see http://feather.elektrum.org/book/src.html) that allows you to pass query parameters to a script in it the SCRIPT’s tag’s SRC attribute just like normal html pages. The problem inside the script is that there are potentially two sets of query data, one for the script (the one we’re after) and one for the page the script is a part of. This last set is access through the usual window.location object.

   1: var scripts = document.getElementsByTagName('script');

   2: var myScript = scripts[ scripts.length - 1 ];

   3:  

   4: var queryString = myScript.src.replace(/^[^\?]+\??/,'');

   5:  

   6: var params = parseQuery( queryString );

   7:  

   8: function parseQuery ( query ) {

   9:    var Params = new Object ();

  10:    if ( ! query ) return Params; // return empty object

  11:    var Pairs = query.split(/[;&]/);

  12:    for ( var i = 0; i < Pairs.length; i++ ) {

  13:       var KeyVal = Pairs[i].split('=');

  14:       if ( ! KeyVal || KeyVal.length != 2 ) continue;

  15:       var key = unescape( KeyVal[0] );

  16:       var val = unescape( KeyVal[1] );

  17:       val = val.replace(/\+/g, ' ');

  18:       Params[key] = val;

  19:    }

  20:    return Params;

  21: }

After which you can simple use it with params[‘course’] or whatever you’re after.

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s