Previous Page
Next Page

Recipe 19.1. Loading Variables from a Text File

Problem

You want to load variables from an external text file into your Flash movie.

Solution

Use the URLLoader.load( ) method in conjunction with DataFormat.VARIABLES as the dataFormat to read URL-encoded data into a Flash movie.

Discussion

You should use the URLLoader.load( ) method whenever you want to load URL-encoded data into your Flash movie from a text file. This technique allows your Flash movie to access values that frequently change without modifying the Flash movie itself.

The load( ) method requires a URLRequest instance as a parameter that points to the URL of the text file. The URL can be an absolute or relative address. Additionally, the URLLoader needs to be configured to interpret the text as URL-encoded variables instead of plain text. Setting the dataFormat property of the URLLoader instance to the DataFormat.VARIABLES constant accomplishes this. Here is code to illustrate loading data from a text file:

import flash.net.*;

// You must first create the URLLoader object.
var example:URLLoader = new URLLoader(  );

// Configure the instance to interpret data as URL-encoded variables
example.dataFormat = DataFormat.VARIABLES;

// This example loads values from a text file at an absolute URL.
example.load( new URLRequest( "http://www.darronschall.com/example.txt" ) );
  
// This example loads values from a text file located at a relative 
// URL, in this case, in the same directory as the .swf file.
example.load( new URLRequest( "example.txt" ) );

Here is an example of what the text file might contain:

someText=testing&someNumber=123

Once you invoke the load( ) method of a URLLoader instance, the Flash Player attempts to load the values from a URL into the data property of the same URLLoader instance. After the data loads, Flash attempts to decode the values and dispatches a complete event when done, signaling that the data is now available in the movie. It is up to you to add an event handler so you can do something useful once the data is loaded and decoded.

In the event that the load fails, the URLLoader dispatches a different type of event based on the type of failure. Therefore, you should not only listen for the complete event on success, but also for any of the failure events.

The failure events that a load( ) call can generate include:



httpStatus

Generated when the Flash Player can detect the status code for a failed HTTP request when attempting to load data.



ioError

Generated when the Flash Player encounters a fatal error that results in an aborted download.



securityError

Generated when data is attempted to be loaded from a domain that resides outside of the security sandbox.

Here is an example of listening for the various events:

package {
  import flash.events.*;
  import flash.net.*;
  import flash.util.trace;

  public class Example {

    public function Example(  ) {
      // Create the URLLoader instance to be able to load data
      var loader:URLLoader = new URLLoader(  );

      // Define the event handlers to listen for success and failure
      loader.addEventListener( IOErrorEvent.IO_ERROR, handleIOError );
      loader.addEventListener( HTTPStatusEvent.HTTP_STATUS, handleHttpStatus );
      loader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, 
                               handleSecurityError );
      loader.addEventListener( Event.COMPLETE, handleComplete );

      // Configure the loader to load URL-encoded variables
      loader.dataFormat = DataFormat.VARIABLES;

      // Attempt to load some data
      loader.load( new URLRequest( "example.txt" ) );
    }

    function handleIOError( event:IOErrorEvent ):void {
      trace( "Load failed: IO error: " + event.text ); 
    }

    function handleHttpStatus( event:HTTPStatusEvent ):void {
      trace( "Load failed: HTTP Status = " + event.status );
    }

    function handleSecurityError( event:SecurityErrorEvent ):void {
      trace( "Load failed: Security Error: " + event.text );
    }

    function handleComplete( event:Event ):Void {
      trace( "The data has successfully loaded" );
    }
}

If loading is successful, the Flash Player stores the loaded variables as properties of the data property of the URLLoader instance and dispatches the complete event. The following example is an event handler for the complete event that accesses known properties loaded from a file. It assumes that there are variables named someText and someNumber in the text file from which the data was loaded:

function handleComplete( event:Event ):void {
  // Cast the event target as a URLLoader instance because that is 
  // what generated the event.
  var loader:URLLoader = URLLoader( event.target );
  
  // Access the variable(s) that were loaded by referencing the 
  // variable name off of the data property of the URLLoader 
  // instance.
  trace( "someText = " + data.someText );
  trace( "someNumber = " + data.someNumber );
}

Here is what the text file might look like:

someText=ActionScript+3.0+Cookbook&someNumber=3

In most cases, you already know the names of the variables that are loaded from the external file or script. For example, you might use a URLLoader instance to load a daily article from a server-side script or file, and regardless of the article's content, you expect three variables (title, author, and articleBody) to be loaded. You know which variables to expect because you wrote the server-side script, work with the person who wrote the script, or have access to documentation on the script. However, there are some situations in which you might not know all the variables that are being loaded. As such, you can use a for . . . in statement to enumerate all the variables that have loaded; for example:

function handleComplete( event:Event ):void {
  var loader:URLLoader = URLLoader( event.target );
  
  // Use a for . . . in loop to loop over all of the variables that 
  // were loaded
  for ( var property:String in loader.data ) {
    // The property name is stored in the property variable, 
    // and the value is retrieved by lookig up the property 
    // off of data.
    trace( property + " = " + loader.data[property] );
  }
}

In previous versions of ActionScript, the loaded variables were added directly to an instance of the LoadVars class. This presented a problem with the loop defined in the preceding code block because property was not always a loaded variable. It was sometimes a regular property of the LoadVars instance, giving false positives for variable names loaded. In ActionScript 3.0, all of the loaded variables are stored in a vanilla data object off of the instance. This makes the preceding loop safe, since property is always the name of a variable that was loaded and never a property of the URLLoader instance itself.


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)