Working on a project we arrived at a point where we needed to read inside the flex application the variables set in the query string. But in the SWF case we have two situations: 1) the query string is in the URL (like yoursite.com/page.php?param1=aaa) and 2) the query string is in the embedded SWF Object (like app.swf?param2=bbb or added using the Javascript code created by Flex Builder).
1) The First case: the query string is in the URL
For this case we access the URL through the Javascript as bellow:
ExternalInterface.call("window.location.search.substring", 1);
After that we need to split the string by “&” and “=” to get the variable/value pairs.
1) The Second case: the query string is in the embedded SWF Object
In this case we have a much simpler situation. Using:
mx.core.Application.application.parameters
we get all we need. You will notice that other parameters are present.
The code of the whole class follows:
import flash.external.*; import flash.utils.*; import mx.core.Application; public class QueryString { private var _queryStringFromUrl:String; private var _paramsFromUrl:Object; private var _noOfParamsFromUrl:uint; private var _noOfParamsFromSwfObject:uint; private var _paramsFromSwfObject:Object; private var _params:Object; private var _noOfParams:uint; /** * getters and setters for the general array containing both * params from URL and from SWF Object **/ public function get parameters():Object { return _params; } public function get noOfParams():uint { return _noOfParams; } public function QueryString() { readQueryString(); getParamsFromSwf(); combineParams(); } /** * method used to read parameters from SWF Object **/ private function getParamsFromSwf():void { _paramsFromSwfObject = mx.core.Application.application.parameters; } /** * method used to read URL query string **/ private function readQueryString():void { _paramsFromUrl = {}; try { _queryStringFromUrl = ExternalInterface.call("window.location.search.substring", 1); if(_queryStringFromUrl) { var params:Array = _queryStringFromUrl.split('&'); var length:uint = params.length; _noOfParamsFromUrl = length; for (var i:uint=0,index:int=-1; i<length; i++) { var kvPair:String = params[i]; if ((index = kvPair.indexOf("=")) > 0) { var key:String = kvPair.substring(0,index); var value:String = kvPair.substring(index+1); _paramsFromUrl[key] = value; } } } } catch(e:Error) { trace("Some error occured. ExternalInterface doesn't work in Standalone player."); } } /** * method used to combine the 2 associative arrays **/ private function combineParams():void { /* * Remove the duplicates from url because the params from SWF Object has priority * Put the new associative array in the newParamsFromUrl */ var newParamsFromUrl:Object = new Object(); for (var tmpC1:* in _paramsFromUrl) { for (var tmpC2:* in _paramsFromSwfObject) { if(tmpC1 == tmpC2) { // do nothing - pass over to eliminate the duplicate } else { newParamsFromUrl[tmpC1] = _paramsFromUrl[tmpC1]; } } } /* * Combine the _paramsFromSwfObject with newParamsFromUrl * No duplicates from this point on * The new array will be accesible throug _params variable and it's getter */ _params = _paramsFromSwfObject; for (var tmpC3:* in newParamsFromUrl) { _params[tmpC3] = newParamsFromUrl[tmpC3]; } /* * Count the number of parameters */ _noOfParams=0; for (var tmpC4:* in _params) { _noOfParams++; } } }
You can use the class like this:
_queryString = new QueryString(); _parameter1 = _queryString.parameters['param1'];
where param1 is the varaible from query-string.
Inspiration came from here but the final class concatenates both parameters from URL and SWF-Object and puts them in one array without duplicates (the parameters in from SWF-Object have overwrites the ones from URL).
Tags: ActionScript, query string, values, variables
This post was written by Andrei Ionescu
Views: 6120



















this is very helpful, but I’m trying to parse a string that is being returned from an ASP script…looks like
array(0)1,mm_name=bluehills.jpg,mm_path=img/req1,mm_keywords=keyword1&array(1)2,mm_name=satellite_map.jpg,mm_path=img/req2,mm_keywords=map satellite&array(2)3,mm_name=robot.jpg,mm_path=img/req2,mm_keywords=robot black and white&
my biggest problem is parsing the values into an array. I’d like to create associative arrays that would hold individual values…
first array holds = mm_name=robot.jpg, mm_name=robot2.jpg,…
second array holds = mm_desc=Robot, mm_desc=Robot2,…
any suggestions are appreciated.
First of all, the string you provided is not a well formed URL so putting it in the browser URL may provide unexpected behaviour, second the following function is in response to what I manage to understand from your comment/request and third is more related to parsing than query strings as you could use other URL formating to get rid of all code I had to write.
] = [,,...]
public function parseYourWay(str:String):Array
{
// remove un-needed array(0)0 thing
var removeArray:RegExp = /\&?array\(\d+\)\d+/g;
// find pairs
var findPairs:RegExp = /([^,]+)=([^,]+)/g;
// here pairs will be stored
var pairs:Array = new Array();
// here the whole string parsed will be as array
// structure:
// foundValue[
// example (this is what the function returns):
// foundValue['mm_keywords'] = ["keyword1","map satellite","robot black and white"];
// foundValue['mm_name'] = ["bluehills.jpg","satelllite_map.jpg","robot.jpg"];
// foundValue['mm_path'] = ["img/req1","img/req2","img/req2"];
var foundValue:Array = new Array();
var tmpStr:String = str.replace(removeArray,"");
// finding pairs
pairs = tmpStr.match(findPairs);
for (var i:int = 0; i < pairs.length; i++) {
// reseting index for exec command
findPairs.lastIndex = 0;
// finding name and values in pairs
var tmpF:Array = findPairs.exec(pairs[i]);
// new array only if not exists otherwise will be overwritten
if (!foundValue[tmpF[1]]) foundValue[tmpF[1]] = new Array();
// adding value found
foundValue[tmpF[1]].push(tmpF[2]);
}
return foundValue;
}
The function can be used as bellow:
var tmp:Array = parseYourWay("array(0)1,mm_name=bluehills.jpg,mm_path=img/req1,mm_keywords=keyword1&arra....");
Thanks Andrei for the solution, but I was unclear as to my goal…
I’m trying to achieve:
var arr:Array = new Array( { uniqueid:"01", mm_name:"cat.jpg", mm_path:"img/req1", mm_keywords:"cat, black cat" },
{ uniqueid:"02", mm_name:"dog.jpg", mm_path:"img/req2", mm_keywords:"dog, brown dog" },
{ uniqueid:"03", mm_name:"elephant.jpg", mm_path:"img/req36", mm_keywords:"elephant, large elephant" }
);
arr.forEach(traceContinent);
function traceContinent(element:*, index:int, arr:Array):void {
trace(element.mm_path + "/" + element.mm_name + "keywords=" + element.mm_keywords);
}
Hi Andrei,
Thanks for this - you have created a lovely object.
Just one thing - I may have found a bug - either that or my implementation of the object is incorrect.
In the combineParams() function, I had to add a couple of extra lines to prevent the html params from being dropped. This happens if the swf params are “undefined” ie not present. Here’s what I added:
private function combineParams():void
{
/*
* Remove the duplicates from url because the params from
* SWF Object has priority
* Put the new associative array in the newParamsFromUrl
*/
var newParamsFromUrl:Object = new Object();
for (var tmpC1:* in _paramsFromUrl)
{
for (var tmpC2:* in _paramsFromSwfObject)
{
if(tmpC1 == tmpC2)
{
// do nothing - pass over to eliminate the duplicate
} else {
newParamsFromUrl[tmpC1] = _paramsFromUrl[tmpC1];
}
}
//added - if swf url was not defined, no url parameters were defined
if ( tmpC2 == undefined ) {
newParamsFromUrl[tmpC1] = _paramsFromUrl[tmpC1];
}
}
…
…
}
private function combineParams():void
{
/*
* Remove the duplicates from url because the params from
* SWF Object has priority
* Put the new associative array in the newParamsFromUrl
*/
var newParamsFromUrl:Object = new Object();
for (var tmpC1:* in _paramsFromUrl)
{
for (var tmpC2:* in _paramsFromSwfObject)
{
if(tmpC1 == tmpC2)
{
// do nothing - pass over to eliminate the duplicate
} else {
newParamsFromUrl[tmpC1] = _paramsFromUrl[tmpC1];
}
}
//added - if swf url was not defined, no url parameters were defined
if ( tmpC2 == undefined ) {
newParamsFromUrl[tmpC1] = _paramsFromUrl[tmpC1];
}
}
…
…
}
hmm…everything looks good, but I simply cannot get this to import the bloody parameters…I’ve tried everything I can think of…and when I simply use the queries as you designate, the flash just can’t pick up my parameters–whether I pass them via an embedded html wrapped link OR directly to the swf. Both ways it refuses to see the information. Any suggestions?
One can use URLVariables Class and a simple regexp to parse the query params into an object.
var url:String = "http://example.com/?param1=test¶m2=sample";
var variables:URLVariables = new URLVariables(url.replace(/.+\?/, ""));
for (var key:* in variables){
trace(key + "=" + variables[key]);
}
Gives us the following output:
param1 = test
param2 = sample
Or just access the query params directly trough the variables object if one knows the param name
var param1:String = variables["param1"];