Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
105
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Chapter 21

Try It Out

Create Ampersand-Delimited Data Using LoadVars

1.Open a new Flash document and save it in your work folder.

2.Click the first frame in the timeline, open the Actions panel, and enter the following ActionScript code:

var myVars:LoadVars = new LoadVars(); myVars.station1 = “Rock and Roll Oldies”; myVars.station2 = “Today’s hit music”;

myVars.station3 = “Electronica in the Nineties”; myVars.station4 = “Electronica Monster 2”; trace(unescape(myVars.toString()));

3.Test the code by pressing Ctrl+Enter. In the output window you will see a neatly constructed ampersand-delimited name/value pair string.

4.Copy the text that you see in the output window into a new document in your favorite text editor. Your resulting file should look like this:

station4=Electronica Monster 2&station3=Electronica in the Nineties&station2=Today’s hit music&station1=Rock and Roll Oldies

5.Save the new text file as myData.txt. Because you’re only using this code to quickly create an example data file for use in the next Try It Out section, you do not need to save your FLA.

How It Works

As you can see, you were able to quickly create your test file by using a simple constructor and simply declaring variables directly upon the LoadVars object.

One important aspect of this code is the use of the unescape() function. Because URLs contain characters and delimiters that can collide with the characters found in variables within GET and POST actions, LoadVars’ toString() method automatically URL-encodes the object. The URL-encoded version of the same code sample would produce the following:

station4=Electronica%20Monster%202&station3=Electronica%20in%20the%20Nineties&stati

on2=Today%E2%80%99s%20hit%20music&station1=Rock%20and%20Roll%20Oldies

As you can see, characters such as ampersands have been converted into percent sign codes. These codes are a percent symbol followed by a numeric identifier. Flash gives you two methods for working with URL encoding: escape() and unescape(). Because the intention was to copy the contents of the LoadVars object to a file, rather than send them to a remote CGI, you use the unescape() function to format the results of the toString() method. You can, in fact, revert the string back to URL-encoded format by using the escape() method. unescape() and escape() work on any string, in any object, not just LoadVars. They can be handy tools when loading data in and out of Flash.

So now that you’ve created and understand a LoadVars object, you can move on to the next and most interesting part of LoadVars, loading remote files!

528

Using ActionScript to Communicate with a Server

LoadVars Event Handlers

Events are specific things that can occur within an application. Many types of events exist. For example, when a user clicks a button an event occurs, and when the playhead enters a frame an event occurs. Flash has mechanisms that listen for events so that code specific to a certain occurrence can run. In the case of LoadVars objects, you’ll want to be notified when the data has downloaded.

Event handlers are methods that get called when an event occurs. By default no functionality is defined for LoadVars event handlers. That is, it is up to you to define these methods for LoadVars objects. In an asynchronous method, such as load(), the application has no idea when the data will arrive, how long it will take when it begins to arrive, or if it will even finish successfully.

The LoadVars class has two such events handler methods: onData() and onLoad().

onData()

The onData() event handler method has one definable parameter, a String object. The method fires as soon as all of the data has arrived from a load() or sendAndLoad() call. If this method is defined, the LoadVars object does not call the onLoad() method. Instead, the raw string data that arrives is sent directly to onData() as a parameter. Here’s the onData() syntax:

myVars.onData = function(str:String):Void { trace(str);

};

onData() makes itself useful by overriding the internal document decoding of the variable file. This means that if what you are loading is unformatted data or uses a different delimitation method, you can still access the string information. You can think of the onData() method as a sort of bypass that routes you directly to the return data requested by the load event.

onLoad()

The onLoad() event handler method has one parameter, a Boolean. onLoad() fires as soon as the object is loaded and has been decoded into a set of variables. Defining the onLoad() method assumes that you believe the return data from the load method will in fact be an ampersand-delimited set of name/value pairs. The Boolean state passed into the function communicates whether the data parsing was successful: true if the data was parsed correctly; false if a parsing error was encountered.

My_Vars.onLoad = function(success:Boolean):Void { if(success){

trace(this);

}

};

onLoad() is helpful because it automates a few steps into one. It lets you know when an object has loaded and if the load was successful, calls the decode method, and then provides you an access point for examining the resulting variables.

Try It Out

Load Ampersand-Delimited Files

1.If you haven’t created the myData.txt file, you should do that now by using your favorite text editor to enter the following text in a file. Save the file as myData.txt.

529

Chapter 21

station4=Electronica Monster 2&station3=Electronica in the Nineties&station2=Today’s hit music&station1=Rock and Roll Oldies

2.Open a new FLA and save it in the same working as myData.txt. Open the Actions panel, and type the following ActionScript code:

var myVars:LoadVars = new LoadVars(); myVars.onLoad = function(success:Boolean):Void {

trace(this.toString());

}

myVars.load(“myData.txt”);

3.Test the code by pressing Ctrl+Enter. The output window shows you the file that has just been loaded in the URL-encoded format.

4.Close the SWF tab and return to the code in the Actions panel. To access some of those variables directly using a for loop, modify the onLoad event to look like this:

var myVars:LoadVars = new LoadVars(); myVars.onLoad = function(success:Boolean):Void {

trace(this.status); if (success) {

for (var i:String in this) {

trace(i+”: “+this[i]);

}

}

};

myVars.load(“myData.txt”);

5.Test the code by pressing Ctrl+Enter. The output window shows you the variable names and values in a list:

station1: Rock and Roll Oldies station2: Today’s hit music station3: Electronica in the Nineties station4: Electronica Monster 2 treeBranch: test=true

onLoad: [type Function]

6.Close the SWF tab and return to the code in the Actions panel. Try out the onData() method and see how you can load your string directly and use the decode method manually. To do so, your code should now look like this:

var myVars:LoadVars = new LoadVars(); myVars.onData = function(str:String):Void {

trace(str);

myVars.decode(str);

trace(this);

};

myVars.load(“myData.txt”);

7.Test the code by pressing Ctrl+Enter. The output window shows you the raw string and variable names and values in a list, much like the following:

530

Using ActionScript to Communicate with a Server

treeBranch=test=true&station4=Electronica Monster 2&station3=Electronica in the Nineties&station2=Today’s hit music&station1=Rock and Roll Oldies

station1: Rock and Roll Oldies station2: Today’s hit music station3: Electronica in the Nineties station4: Electronica Monster 2 treeBranch: test=true

onData: [type Function]

8.Close the SWF tab and save your FLA file. You reuse this code in a later Try It Out section.

How It Works

The load() method is an asynchronous operation. The time is reliant upon the speed at which Flash can import the file. If this file had been on the Internet, it may have taken more than a few seconds to load the byte data of the file into Flash. By setting an event handler, you’ve allowed the code the flexibility it needs to complete a useful file load.

The other look you had was at onData(). You saw that you could, in fact, load a raw text file and disallow Flash from doing anything with it on its own. This is handy, because sometimes you don’t have control over remote file format. There may be times you want to load a file that is neither ampersanddelimited nor value pairs. In these cases you can use the onData() method to load the file directly and use String methods on the str value to extract the data you need by hand.

When using the onLoad() event, you assume you’re loading an ampersand-delimited formatted document. This has the advantage of sending the event a Boolean telling you whether the file load was successful. onLoad() also calls the decode all by itself, so you didn’t have to worry about that step.

Loading and Parsing Raw Text

At times the data you have available to you is not formatted as ampersand-delimited name/value pairs. Sometimes the data has its own unique format, or the data is a paragraph of text. Sometimes you might want to obtain data that resides within HTML files. In these cases, you need to build your own parsing routine.

The most common (String class) methods for working such strings are split() and join(). For the purposes of this chapter, you will be loading a simple HTML file and using LoadVars and the String class to extract data from the HTML page.

The example is going to find and show you an <a href> tag from any HTML file. You can query Slashdot, or Google, or an Apache HTTP folder listing of JPEG images. For this example, you’ll be loading Slashdot, mostly for the irony and plethora of links about robots.

Because you know how to load raw string data from the previous Try It Out examples, this section shows you code that can manipulate the string itself, without getting too far into the details of the String class. This should give you a good start on how to create your own text parsers.

531

Chapter 21

Of course, loading cross-domain files still has the same issues, and loading someone else’s web page from another domain directly into a Flash document on your own domain won’t work without security considerations. A couple of sections about security in Chapter 22 explain what the limitations are and how to deal with them.

The following Try It Out contains concepts from several chapters.

Try It Out

Load a Raw String and Do Something Neat!

1.Open a new Flash document and define a function that can find and extract an href link from a string:

findAHrefLinks = function (page:String):Object { var linkList:Object = {};

var ahrefs:Array = page.split(“<a”); ahrefs.shift();

for (var i:Number = 0; i<ahrefs.length; i++) { ahrefs[i] = ahrefs[i].split(“/a>”)[0];

}

for (var i:Number = 0; i<ahrefs.length; i++) {

var thisLink:Object = linkList[“link”+i]={}; var linkText:String = ahrefs[i].split(“>”)[1];

linkText = linkText.substring(0, linkText.lastIndexOf(“<”));

thisLink.linkText = linkText; var attributes:Array = ;

ahrefs[i].split(“>”)[0].split(‘“‘).join(“”).split(“‘“).join(“”); thisLink.url = attributes.split(“href=”)[1];

if (thisLink.url.indexOf(“ “)>1) {

thisLink.url = thisLink.url.substring(0, ; thisLink.url.indexOf(“ “));

}

}

return linkList;

};

2.Load a web page into a LoadVars object and run the raw string through your new function using onData() by adding the following code to the end of the code you entered in step 1:

var myVars:LoadVars = new LoadVars(); var baseUrl:String = “slashdot.com”;

myVars.onData = function(str:String):Void {

var linkList:Object = findAHrefLinks(str); for(var i:String in linkList){

trace(newline);

for(var n:String in linkList[i]){ trace(n+”: “+linkList[i][n]);

}

}

};

myVars.load(“http://”+baseUrl);

532

Using ActionScript to Communicate with a Server

3.Test the code by pressing Ctrl+Enter. After a few moments, as long as you have access to Slashdot via your Internet connection, you will see a list of links in the output window similar to the following:

url: //slashdot.org/login.pl?op=newuserform linkText: Create a new account

url: //ask.slashdot.org/article.pl?sid=05/07/25/2133209 linkText: Software Engineering vs. Systems Engineering?

url: //ask.slashdot.org/article.pl?sid=05/07/26/1811247 linkText: How Should One Respond to a Network Break In?

url: //ask.slashdot.org/article.pl?sid=05/07/26/1857254 linkText: Free Audio Content for Long Drives?

url: //ask.slashdot.org/article.pl?sid=05/07/26/1932206 linkText: Fun and Informative Way to Introduce Open Source?

4.Save the FLA file if you want. Experiment with the attributes variable declaration and see whether you can find any attributes other than the href value.

How It Works

In the function that finds href attributes, there is a split() method that effectively finds all instances of the <a> tag. This is followed up by a loop that finds the end tag of those, effectively discarding all other content in the string by selectively keeping only the 0 index of the array created by the split.

The next for loop extracts the link text from within the tag by using split once again, but saving only what comes after the first end bracket by using the 1 index of the array created by the split method. The next line simply cleans up trailing open brackets by cutting the string with the substring method. The link text is added to the outgoing object.

The value of the variable attributes appears complex, but it’s not. Two things are happening. First you split the tag once again, this time keeping everything that precedes the first closing bracket. This effectively yields all the attributes within that <a> tag as a single string. There is one caveat. The <a> tag attributes reside within quotes. By using split and join consecutively, you are effectively doing a find/replace operation on the string, only the replacement is a zero-length string, which removes all single and double quotes.

The next thing that happens is that the URL is extracted from the attributes variable. This is done by splitting the string “href” and keeping all of the trailing text. Because this may not be the last attribute listed within the tag, you search for the first space using indexOf() and assume this is the end of the URL. Using substring, the URL is cut from any trailing text.

And that’s it. The last line of the function returns the linkList as an object to the requesting object in the onData() method. You could then test the URL values, add the baseUrl as needed, and complete a list of working links on your stage using HTML-enabled text fields.

533

Chapter 21

Hopefully, this gave you a sense of the power of loading raw strings. As an exercise you could go back into the function and make it more efficient. Places within the code are drawn out so you can see better the inner workings of the operation. You could try to find more attributes such as class, or id, and parse the CSS information from the same HTML page. You could then re-create the links on the stage using the exact style format as the web page. You could, in fact, begin to build a simplified XHTML browser with CSS styles. There’s really no limit to what you can do when Flash is able to communicate with a server with this much freedom. Have fun!

Summar y

In this chapter you explored working with the LoadVars class. You learned that you can load data in ampersand-delimited format, and that Flash will automatically parse that data into variables. You’ve also learned how to load raw text so that Flash does not parse the data.

Exercises

1.Create a pipe (|) delimited file, rather than an ampersand-delimited file. Load the data file as a raw string using the LoadVars object. Parse the name/value pairs and place them within an object.

2.Load HTML text from a file, and display it in an HTML-enabled text field.

534

22

Reading XML

This chapter introduces the many ways in which XML files can be loaded into your application at runtime. Once the XML is loaded, you see how you can use Flash’s robust XML toolset to access and utilize the data presented. You also examine security concerns that affect the success of XML in your application and explore solutions to security restrictions such as proxies, shims, and policy files.

Using the Built-in XML Class

Luckily Flash is a platform that is constantly in development. Because Flash is constantly being updated, its input and output methods are constantly under scrutiny. You have new classes and methods with almost every release. These additions can include class sets for SOAP (don’t worry about what this is; more about SOAP later) and drag-and-drop components for quickly connecting your Flash application to remote servers for data transactions. This section concerns itself with the most recent and native XML data transport methods available in AS2, introducing you to the methods and objects designed for XML-based data interactions.

One thing to remember is that when you start diving into XML you’ll hear fancy terms such as DOM, DTD, XSL, Schemas, SOAP, RPC, and more. Do not be afraid. At the end of the day, XML is simply a markup text similar to HTML. XML’s power is its logical simplicity. Flash’s XML object is, in fact, a great way to begin working with XML for the first time because of the simplicity and tolerances built into the Flash XML object.

All Wrapped Up in Tags

XML is a way of hierarchically representing information so that meaningful data relationships can be shared among applications. XML is a specification maintained by the W3C. Like HTML, XML uses tags to define data. The same hierarchical concepts are used in HTML and XML. A tag placed within a tag is a child of the outer tag. Here is an HTML example of a <div> tag with a child <p> tag child:

...<div>

<p>This is div number 1!</p> </div>...

Chapter 22

In this case, <div> is the parent of <p> (and <p> is the child of <div>). As with HTML, you can populate XML tags with attributes, and you can leave raw text within a tag. Unlike HTML, XML is not restricted in any way to naming conventions or preset attribute expectations. You are free to make up naming conventions. Although HTML tells an application how data should look, XML informs an application what the data is and how different data sets relate to one another.

You’ll be using a simple XML file example because it easily showcases all of the methods available in Flash and demonstrates how powerful XML can be even in simple contexts. Here’s a very simple XML file:

<menu>

<hoopty>

<automobile doors=”4” color=”white”> Chrysler 300m</automobile> <automobile doors=”2” color=”silver”> Porsche Cayenne</automobile> <truck doors=”24” color=”black” >Cadillac Escalade</truck>

</hoopty>

</menu>

In it, you create a menu of cars, classified by type and given attributes that describe them. hoopty is an element. An element name can’t contain spaces or start with a special character such as a dollar sign. The other way in which you have encapsulated data is the use of attributes within some tags. Attribute values must be wrapped in quotes, no matter the data type described. A case for using attributes is when the data being described within the attribute has no possible children. That is, it is not an element that can contain elements.

windows is an example of an attribute that may be better suited as an element:

<menu>

<hoopty>

<automobile windows=”tinted” doors=”4” color=”white”> Chrysler 300m</automobile>

<automobile windows=”tinted” doors=”2” color=”silver”> Porsche Cayenne</automobile>

<truck doors=”24” color=”black” >Cadillac Escalade</truck> </hoopty>

</menu>

Although this seems to have served the purpose, you can imagine that there may be different types of windows.

Here is an example in which using an element rather than an attribute enables you to grow your XML file without much modification:

<menu>

<hoopty>

<automobile doors=”4” color=”White”> <name>Chrysler 300m</name> <window>

<type>tinted</type>

<color>Black</color>

</window>

</automobile>

<automobile doors=”2” color=”Silver”> <name>Porsche Cayenne</name> <window>

536

Reading XML

<type>tinted</type>

<color>Crimson</color>

</window>

</automobile>

<automobile doors=”9” color=”Black”> <name>Cadillac Escalade</name> <window>

<type>tinted</type>

<color>Black</color>

</window>

</automobile>

</hoopty>

</menu>

You can see that by making the window attribute an element you were able to expand the description logically, while allowing data to be removed or added at any time.

Although this description of XML certainly isn’t all-encompassing, it’s just what you need to know to get started with the XML class in Flash.

CDATA and Character Formats

XML elements can also contain HTML characters. These HTML strings can disrupt an XML schema because it cuts through the hierarchical document with its own tags. The W3C standard provides you with CDATA tags, and, happily, Flash complies with the specification. CDATA tags simply tell the application reading the XML to not parse any information within a CDATA tag as a child node. Flash handles these strings by declaring them text nodes.

Here is an example of a CDATA wrapper:

... <automobile doors=”4” color=”White”>

<image><![CDATA[ <img src=’myimage.gif’/>]]></image> <name>Chrysler 300m</name>

<window>

<type>tinted</type>

<color>Black</color>

</window> </automobile>...

In this example, an <img> tag is assigned as the text node value for the XML<image> element. Because the text is an HTML tag, it is wrapped in a CDATA wrapper. CDATA is preceded by <![CDATA[ and followed by ]]>.

The Flash XML Class

In Flash, XML is a built-in class. It has a set of useful properties, methods, and events that enable you to complete a feature-rich data exchange. Setting up an XML object within your ActionScript is as easy as a simple object type definition. XML is a globally accessible class available via the keyword new:

var myXML:XML = new XML();

537