Mike T. Henderson

Interactive Design & Art Direction

Return Variable Value From Query String

Jan 2 2008

I recently came across a case where I needed to use a query string in my URL to determine which content to display in my Flash. I learned that returning a query string can be as simple as using the ExternalInterface.call() method.

For example. If your URL looks like; http://www.yoururl.com/?name=mike, then to return the query string all you would have to do is:

import flash.external.ExternalInterface;
var query:String = ExternalInterface.call("document.location.search.toString");

Your query variable would then equal "?name=mike". In order to get your value, you could then turn your value into an array using query.split("") and do a loop that cycles through the string and returns every thing after the "=" sign. However, since I was using a query string that was generated from a Google Analytics URL, I was faced with having multiple variables in my string.

My solution ended on wanting a class that allowed you to call a variable name, and then return the value.

import flash.external.ExternalInterface;
 
class getQueryValue {
 
private static var match:Boolean = false;
private static var searchTerm:String;
 
static function getValue (args:Object):String {
 
// get full query string
var query = ExternalInterface.call("document.location.search.toString");
 
// build array
var qarray = query.split("");
 
for (var i:Number = 0; i
 
// build search term
if (qarray[i] != "?" && qarray[i] != "=" && qarray[i] != "&") {
searchTerm += qarray[i];
}
 
// check to see if search term is a var or the last value in the search
if (qarray[i] == "?" || qarray[i] == "&" || i == qarray.length-1) {
if (match == true) {
return searchTerm;
break;
}
searchTerm = "";
}
 
// check to see if search term matches the defined var name
if (qarray[i] == "=") {
if (searchTerm == args.queryVar) {
match = true;
}
searchTerm = "";
}
}
}
}

To call the class, place it in the same directory as the .fla file when you export and place the following code on the first frame of your actions:

var queryValue = getQueryValue.getValue({queryVar:"name"})

This class has one object parameter called "queryVar". What this does is take the name of the variable that you wish to return from the query string, and cycles through the entire string searching for that variable name and then returning its value. For example, if your URL looks like; http://www.yoururl.com/?name=mike&age=26, using the same line of code from above, the variable queryValue will equal "mike".

0 Posted under: Strings

Leave a Reply