Decoding URL encoded strings in a Flash application using the URLVariables class in ActionScript 3.0

by Peter deHaan on February 27, 2008

in LoadVars, URLVariables, migration

The following examples show how you can parse URL encoded strings using ActionScript 2.0 and ActionScript 3.0.

Full code after the jump.

The following example shows how you can use the LoadVars class and the decode() method to parse a URL encoded string:

// ActionScript 2.0
var loadVars:LoadVars = new LoadVars();
loadVars.decode("firstName=Tom&lastName=Jones");
lbl.text = loadVars.lastName + "," + loadVars.firstName;

In ActionScript 3.0, you can use one of two methods. The first method passes the string to be decoded to the URLVariables class constructor:

// ActionScript 3.0
var urlVariables:URLVariables = new URLVariables("firstName=Tom&lastName=Jones");
lbl.text = urlVariables.lastName + "," + urlVariables.firstName;

The second method is similar to the ActionScript 2.0 approach and uses the decode() method to parse the URL encoded string:

// ActionScript 3.0
var urlVariables:URLVariables = new URLVariables();
urlVariables.decode("firstName=Tom&lastName=Jones");
lbl.text = urlVariables.lastName + "," + urlVariables.firstName;

{ 3 comments… read them below or add one }

1 Régis 01.27.09 at 11:09 am

Just a little correction

// Suppose there's a variable ldap inside a txt
//&ldap=blah blah
// Instantiate like myMap:Map = new Map("filename.txt");
 
package {
    import flash.events.*;
    import flash.net.*;
    public class Map {
 
        public function Map(file:String):void {
            var url:URLRequest = new URLRequest(file);
            var infoTxt:URLLoader = new URLLoader();
            infoTxt.dataFormat = URLLoaderDataFormat.TEXT;
            infoTxt.load(url);
            infoTxt.addEventListener(Event.COMPLETE, readTxtFile);
 
            function readTxtFile( evt:Event ):void {
                var urlVariables:URLVariables = new URLVariables(infoTxt.data);
                //for (var prop:String in urlVariables)
                    trace("Variable ldap: "+urlVariables.ldat);
            }
        }
    }
}
2 Najeeb 12.10.09 at 9:14 pm

Very helpful….I was wondering how do you deal with name value pairs in URLVariable. Lets say I have an array of name value pairs.
Thanks

3 alex 12.14.09 at 4:19 am

var urlVariables:URLVariables = new URLVariables(infoTxt.data);
must be
var urlVariables:URLVariables = new URLVariables(evt.target.data);

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Previous post:

Next post: