Mike T. Henderson

Interactive Design & Art Direction

Return Query Value -- Version 2

Feb 2 2009

http://www.mikethenderson.com?name=mike&age=27

A while back I created a little ActionScript 3 class, using the ExternalInterface.call method, that returns a query string value from the url. This came in pretty handy for things such as direct linking to certain videos within a video player, displaying campaign specific content on load based on different referring sites, ect, etc.

Upon second glance, I realized that I got a little loop-happy with the previous attempt. Below is a slimmer version with the redundancies taken out.

 
package com {
 
	import flash.external.ExternalInterface;
 
	public class QueryString {
 
		private static var _match:Boolean;
		private static var _value:String;
 
		public function QueryString() {
			// constructor
		}
 
		public static function getQueryValue ( qvar:String ):String {// reset vars
			_match = false;
			_value = "";
 
			// get full query string
			var _query:String = ExternalInterface.call("document.location.search.toString");
 
			// remove question mark
			_query = _query.substring( 1, _query.length );
 
			var qarray = _query.split( "&" );
 
			for ( var i = 0; i < qarray.length; i ++ ) {
 
				if ( qarray[ i ].split( "=" )[ 0 ] == qvar ) {
					_value = qarray[ i ].split( "=" )[ 1 ];
					break;
				}
 
			}
 
			return _value;
		}
 
	}
 
}
 

Public Static Methods:
getQueryValue( qvar:String ):String -- returns value of var name from query string in url

Properties of getQueryValue():
qvar:String -- name of variable you wish to retrieve value from

Usage Example:

 
import com.QueryString;
// create text field
var myQValue:TextField = new TextField();
// add to display list
addChild( myQValue );
// if query string = ?name=mike&#038;age=27
myQValue.text = QueryString.getQueryValue("name"); // returns mike
 
2 Posted under: Strings

2 Responses

  1. Greg says:

    Sweet.
    Exactly what I needed. Thanks.

  2. Jason L says:

    If you want to remove even more loops at the cheap cost of some memory (if your site needs access to these parameters often) just consider keeping an array of previous arguments already parsed as a class array. Keeps those expensive string ops down.

    Before even splitting just see if you've already parsed that value.. just run a quick check to see if you already know it ala if (_parsedValues[qvar] != undefined) { return _parsedValues[qvar]; } before you ever even split or loop.

Leave a Reply