ActionScript 3.0 includes mechanisms for loading data from external sources. Those sources can be static content such as text files, or dynamic content such as a web script that retrieves data from a database. The data can be formatted in a variety of ways, and ActionScript provides functionality for decoding and accessing the data. You can also send data to the external server as part of the process of retrieving data.
ActionScript 3.0 uses the URLLoader and URLVariables classes for loading external data. The URLLoader class downloads data from a URL as text, binary data, or URL-encoded variables. The URLLoader class is useful for downloading text files, XML, or other information to use in dynamic, data-driven ActionScript applications. The URLLoader class takes advantage of the ActionScript 3.0 advanced event-handling model, which allows you to listen for such events as complete, httpStatus, ioError, open, progress, and securityError. The new event-handling model is a significant improvement over the ActionScript 2.0 support for the LoadVars.onData, LoadVars.onHTTPStatus, and LoadVars.onLoad event handlers because it allows you to handle errors and events more efficiently. For more information on handling events, see Handling events
Much like the XML and LoadVars classes in earlier versions of ActionScript, the data of the URLLoader URL is not available until the download has completed. You can monitor the progress of the download (bytes loaded and bytes total) by listening for the flash.events.ProgressEvent.PROGRESS event to be dispatched, although if a file loads too quickly a ProgressEvent.PROGRESS event may not be dispatched. When a file has successfully downloaded, the flash.events.Event.COMPLETE event will be dispatched. The loaded data is decoded from UTF-8 or UTF-16 encoding into a string.
The URLLoader.load() method (and optionally the URLLoader class's constructor) takes a single parameter, request, which is a URLRequest instance. A URLRequest instance contains all of the information for a single HTTP request, such as the target URL, request method (GET or POST), additional header information, and the MIME type (for example, when you upload XML content).
For example, to upload an XML packet to a server-side script, you could use the following ActionScript 3.0 code:
var secondsUTC:Number = new Date().time;
var dataXML:XML =
<login>
<time>{secondsUTC}</time>
<username>Ernie</username>
<password>guru</password>
</login>;
var request:URLRequest = new URLRequest("http://www.yourdomain.com/login.cfm");
request.contentType = "text/xml";
request.data = dataXML.toXMLString();
request.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
try
{
loader.load(request);
}
catch (error:ArgumentError)
{
trace("An ArgumentError has occurred.");
}
catch (error:SecurityError)
{
trace("A SecurityError has occurred.");
}
The previous snippet creates an XML instance named dataXML that contains an XML packet to be sent to the server. Next, you set the URLRequest contentType property to "text/xml" and set the URLRequest data property to the contents of the XML packet, which are converted to a string by using the XML.toXMLString() method. Finally, you create a new URLLoader instance and send the request to the remote script by using the URLLoader.load() method.
There are three ways in which you can specify parameters to pass in a URL request:
When you define variables within the URLVariables constructor or within the URLVariables.decode() method, you need to make sure that you URL-encode the ampersand character because it has a special meaning and acts as a delimiter. For example, when you pass an ampersand, you need to URL-encode the ampersand by changing it from & to %26 because the ampersand acts as a delimiter for parameters.
When you build dynamic applications with ActionScript 3.0, it's a good idea to load data from external files or from server-side scripts. This lets you build dynamic applications without having to edit or recompile your ActionScript files. For example, if you build a "tip of the day" application, you can write a server-side script that retrieves a random tip from a database and saves it to a text file once a day. Then your ActionScript application can load the contents of a static text file instead of querying the database each time.
The following snippet creates a URLRequest and URLLoader object, which loads the contents of an external text file, params.txt:
var request:URLRequest = new URLRequest("params.txt");
var loader:URLLoader = new URLLoader();
loader.load(request);
You can simplify the previous snippet to the following:
var loader:URLLoader = new URLLoader(new URLRequest("params.txt"));
By default, if you do not define a request method, Flash Player and Adobe AIR load the content using the HTTP GET method. If you want to send the data using the POST method, you need to set the request.method property to POST using the static constant URLRequestMethod.POST, as the following code shows:
var request:URLRequest = new URLRequest("sendfeedback.cfm");
request.method = URLRequestMethod.POST;
The external document, params.txt, that is loaded at run time contains the following data:
monthNames=January,February,March,April,May,June,July,August,September,October,November,December&dayNames=Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
The file contains two parameters, monthNames and dayNames. Each parameter contains a comma-separated list that is parsed as strings. You can split this list into an array using the String.split() method.
Avoid using reserved words or language constructs as variable names in external data files, because doing so makes reading and debugging your code more difficult.Once the data has loaded, the Event.COMPLETE event is dispatched, and the contents of the external document are available to use in the URLLoader's data property, as the following code shows:
private function completeHandler(event:Event):void
{
var loader2:URLLoader = URLLoader(event.target);
trace(loader2.data);
}
If the remote document contains name-value pairs, you can parse the data using the URLVariables class by passing in the contents of the loaded file, as follows:
private function completeHandler(event:Event):void
{
var loader2:URLLoader = URLLoader(event.target);
var variables:URLVariables = new URLVariables(loader2.data);
trace(variables.dayNames);
}
Each name-value pair from the external file is created as a property in the URLVariables object. Each property within the variables object in the previous code sample is treated as a string. If the value of the name-value pair is a list of items, you can convert the string into an array by calling the String.split() method, as follows:
var dayNameArray:Array = variables.dayNames.split(",");
If you are loading numeric data from external text files, you need to convert the values into numeric values by using a top-level function, such as int(), uint(), or Number(). Instead of loading the contents of the remote file as a string and creating a new URLVariables object, you could instead set the URLLoader.dataFormat property to one of the static properties found in the URLLoaderDataFormat class. The three possible values for the URLLoader.dataFormat property are as follows:
The following code demonstrates how setting the URLLoader.dataFormat property to URLLoaderDataFormat.VARIABLES allows you to automatically parse loaded data into a URLVariables object:
package
{
import flash.display.Sprite;
import flash.events.*;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
public class URLLoaderDataFormatExample extends Sprite
{
public function URLLoaderDataFormatExample()
{
var request:URLRequest = new URLRequest("http://www.[yourdomain].com/params.txt");
var variables:URLLoader = new URLLoader();
variables.dataFormat = URLLoaderDataFormat.VARIABLES;
variables.addEventListener(Event.COMPLETE, completeHandler);
try
{
variables.load(request);
}
catch (error:Error)
{
trace("Unable to load URL: " + error);
}
}
private function completeHandler(event:Event):void
{
var loader:URLLoader = URLLoader(event.target);
trace(loader.data.dayNames);
}
}
}
As the following example shows, Loading XML from an external file is the same as loading URLVariables. You can create a URLRequest instance and a URLLoader instance and use them to download a remote XML document. When the file has completely downloaded, the Event.COMPLETE event is dispatched and the contents of the external file are converted to an XML instance, which you can parse using XML methods and properties.
package
{
import flash.display.Sprite;
import flash.errors.*;
import flash.events.*;
import flash.net.URLLoader;
import flash.net.URLRequest;
public class ExternalDocs extends Sprite
{
public function ExternalDocs()
{
var request:URLRequest = new URLRequest("http://www.[yourdomain].com/data.xml");
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
try
{
loader.load(request);
}
catch (error:ArgumentError)
{
trace("An ArgumentError has occurred.");
}
catch (error:SecurityError)
{
trace("A SecurityError has occurred.");
}
}
private function completeHandler(event:Event):void
{
var dataXML:XML = XML(event.target.data);
trace(dataXML.toXMLString());
}
}
}
In addition to loading external data files, you can also use the URLVariables class to send variables to a server-side script and process the server's response. This is useful, for example, if you are programming a game and want to send the user's score to a server to calculate whether it should be added to the high scores list, or even send a user's login information to a server for validation. A server-side script can process the user name and password, validate it against a database, and return confirmation of whether the user-supplied credentials are valid.
The following snippet creates a URLVariables object named variables, which creates a new variable called name. Next, a URLRequest object is created that specifies the URL of the server-side script to send the variables to. Then you set the method property of the URLRequest object to send the variables as an HTTP POST request. To add the URLVariables object to the URL request, you set the data property of the URLRequest object to the URLVariables object created earlier. Finally, the URLLoader instance is created and the URLLoader.load() method is invoked, which initiates the request.
var variables:URLVariables = new URLVariables("name=Franklin");
var request:URLRequest = new URLRequest();
request.url = "http://www.[yourdomain].com/greeting.cfm";
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, completeHandler);
try
{
loader.load(request);
}
catch (error:Error)
{
trace("Unable to load URL");
}
function completeHandler(event:Event):void
{
trace(event.target.data.welcomeMessage);
}
The following code contains the contents of the Adobe ColdFusion® greeting.cfm document used in the previous example:
<cfif NOT IsDefined("Form.name") OR Len(Trim(Form.Name)) EQ 0>
<cfset Form.Name = "Stranger" />
</cfif>
<cfoutput>welcomeMessage=#UrlEncodedFormat("Welcome, " & Form.name)#
</cfoutput>