Macromedia Flash MX ActionScripting: Advanced Training from the Source

It's time to start using some XML! Nearly everything you do with XML in Flash involves the XML object and falls into one of the following categories: formatting XML, parsing XML (extracting the information), loading XML, or sending XML. With the XML object you will be able to load XML from an external source such as a static file or a server side script. Once this XML document is loaded you can access its information using the methods and properties of the XML object. Also using the methods and properties of the XML object you can create your own XML document. Once this document is created you can use it in your Flash movie or send it out to a server side script. All the ActionScript needed to do these things is covered in this section.

Formating XML

The XML object in Flash has several methods, all of which you can use to create and format XML documents. Truth is, though, you're unlikely to employ them because they're difficult to use and there's a better way! We'll show you how to create a string and then convert it into an XML object a much easier (and more common) way of formatting XML objects.

To create an XML object in Flash, you must use its constructor. Here is how you would create an empty XML object:

myXML = new XML();

To populate the object with XML-formatted data when it is created, you can pass (inside the parentheses of the constructor) the name of a variable that holds an XML-formatted string or another XML object.

If, in Flash, we wanted to create the following XML document:

<MyFriends> <Name Gender="female">Kelly Makar</Name> <Name Gender="male">Free Makar</Name> </MyFriends>

We would do two things:

  1. Create the document as a string.

  2. Convert the string to an XML object using the XML object constructor, new XML().

Here is an example:

myString = "<MyFriends><Name Gender=\"female\">Kelly Makar</Name><Name Gender=\"male\">Free Makar</Name></MyFriends>"; myXML = new XML(myString);

The above ActionScript creates the XML document as a string and then converts it to an actual XML object called myXML . This object can then be sent to the server using the send-related methods described later in this section of the lesson.

Parsing XML

The word parse simply means to analyze something or break it down into its parts. Thus, when someone speaks of writing a script to parse an XML document, they're talking about writing a script that extracts information from that XML document. The XML object has many properties to help you do this. We'll use the XML object you created in the previous subsection, myXML , to illustrate the use of a few of the most common properties.

firstChild : This property points to the first node in the tree structure. For example: myXML.firstChild.firstChild returns <Name Gender="female">Kelly Makar</Name> . The first child node of the XML document is the root node (MyFriends ) and the root node's first child is Name , as shown.

childNodes: This property returns an array of the child nodes at any given point in the tree structure. For instance: myArray = myXML.firstChild.childNodes . Here, myArray contains two elements whose values are the same as those of the two Name nodes.

nextSibling: This property points to the next node in the same level of the tree structure. Thus, myXML.firstChild.firstChild.nextSibling returns <Name Gender="male">Free Makar</Name>.

attributes : This property returns an associative array of attribute names. For instance: myXML.firstChild.firstChild.nextSibling.attributes.Gender returns "male" .

The above represent the most commonly used properties of the XML object; others work in the same way, referencing different parts of the tree structure.

Loading XML

Typically, you'll only work with XML in Flash when you're loading it or sending it out. To load XML from a remote source, you would do the following:

  1. Create an XML object.

  2. Use the load() method of the XML object to load XML-formatted data from an external source.

For example:

myXML = new XML(); myXML.load("http://somedomain.com/info.xml");

Although in this example, the document being loaded is a static XML file, it doesn't have to be. It can point to an ASP page (or another scripted page) whose result is an XML document.

It's easy to determine when the XML has finished loading into an object by using the onLoad event available to the XML object. You can define this event to call a function when the document is finished loading. Take a look at the following example:

function init () { //parse script here } myXML = new XML(); myXML.onLoad = init; myXML.load("http://somedomain.com/info.xml");

As the second line from the bottom shows, when the XML document is finished loading, the init function will be called.

Sending XML

The XML object allows you to send XML to a URL. It also lets you send XML and load the resulting document simultaneously.

To send XML to a URL, use the send() method and specify a destination URL. For instance:

myXML = new XML("<Message><Text>Hi!</Text></Message>"); myXML.send("http://somedomain.com/somedestination.asp");

To send XML and receive a response, all in one shot, use the sendAndLoad() method of the XML object. With this method, you must specify an XML object whose contents you wish to send, a URL in which to send the XML document, and an XML object in which to receive the response. As shown with the load() example in the previous subsection, you must define an onLoad event to handle the loaded XML. Here is an example:

URL = "http://www.electrotank.com/projects/tfts/using_xml/UserLogin.asp"; function init () { trace(objToReceive); } xmlToSend = "<Login><UserName>Jobem</UserName><Password>hayes</Password></Login>"; objToSend = new XML(xmlToSend); objToReceive = new XML(); objToReceive.onLoad = init; objToSend.sendAndLoad(URL, objToReceive);

The above ActionScript creates an XML object (objToSend ) containing log-in information, and then sends that information to a URL where it waits for a response from the destination. When the response is fully loaded into the receiving XML object (objToReceive ), the init function is called.

Now that you know a little bit about the XML format and XML objects (as well as their objects and properties), it's time to put that knowledge to use! In this section, you'll format a few simple XML documents, perform some easy parsing, and use sendAndLoad() to create a simple Flash application that acts as a registration/log-in screen.

The Flash file used in this section communicates with ASP pages. To fully build and test this file, you'll need access to a server where you can run ASP scripts (which usually means a Windows server). To test the files in this exercise, you'll need to upload two ASP files (AddUser.asp and UserLogin.asp) and one MS Access database file (XMLExample.mdb) to the same directory on a Windows server. (These files can be found in the Lesson12/Assets folder.)

The AddUser.asp page accepts an XML document structured as follows:

<Register> <UserName>jobem</UserName> <Email>jobe@electrotank.com</Email> <Password>secret</Password> </Register>

If the user was registered properly, this page (AddUser.asp) will return the following result:

<Register> <Message>User Inserted</Message> </Register>

If a user of the same name already exists, it will return this result instead:

<Register> <Message>User Exists</Message> </Register>

The UserLogin.asp page accepts an XML document structured as follows:

<Login> <UserName>jobem</UserName> <Password>secretword</Password> </Login>

If the information provided was correct, this page returns the following result:

<Login> <Message>Login Correct</Message> </Login>

If the information provided was incorrect, the page returns this result instead:

<Login> <Message>Login Incorrect</Message> </Login>

  1. Open LoginRegister1.fla from the Lesson12/Assets directory.

    We've already created all of the frames, text fields, and buttons in this file. The file contains four layers: The Actions layer is where we'll write all of the ActionScript; the Labels layer contains the frame labels we need; the Assets layer contains text fields and buttons; and the Background layer contains the interface graphics.

  2. With the Actions panel open, select Frame 1 and add a stop() action.

    By placing the Stop action here, we prevent the movie from automatically playing.

  3. With the Actions panel open and the timeline at Frame 1, select the Login button and add this script:

    on (release) { _root.gotoAndStop("login"); }

    When the user clicks this button, he or she will be taken to the log-in frame (where he or she can log in).

  4. With the Actions panel open and the timeline at Frame 1, select the Register button and add this script:

    on (release) { _root.gotoAndStop("register"); }

    When the user clicks this button, she will be taken to the register frame where she'll be able to register a new account.

  5. Move the playhead to the frame labeled Login. At this label, you will find two text fields (userName and password) and a button on the stage. With the Actions panel open, select the frame on the Actions layer at that label and add the following line of script:

    loginURL = "http://yourdomain.com/projects/tfts/using_xml/UserLogin.asp";

    This is the ASP page that accepts the log-in XML document. It will parse the document that you send and return an answer to let you know whether the user provided the correct information. Make sure you enter the correct path to the file that you uploaded.

  6. With the same frame still selected, add this function definition:

    function loginSubmit () { xmlToSend = "<Login><UserName>"+userName.text+"</UserName><Password>"+password.text+"</P assword></Login>"; objToSend = new XML(xmlToSend); objToReceive = new XML(); objToReceive.onLoad = loginResponse; objToSend.sendAndLoad(loginURL, objToReceive); _root.gotoAndStop("waiting"); }

    Although it hasn't been scripted to do so yet, this function will be called when the Submit button (currently on the stage) is pressed. The first line of the function uses the values entered in the userName and password text fields to format the XML that we're sending to the ASP page and then places that formatted data into a string variable named xmlToSend . Next, we create a new XML object named objToSend and pass into it the XML-formatted string we just created. The reason for doing this is that the sendAndLoad() method only works with XML objects we can't apply it to a string. Next, we create a new object named objToReceive . This is the XML object that the ASP page's response is loaded into. Next, using the onLoad event, we tell the objToReceive object to call the loginResponse() function once the XML data has been loaded into it. (We'll create the loginResponse() function in the next step.

    The next action in the function invokes the sendAndLoad() method by specifying the object to send, the destination URL, and the object in which to load the response. Finally, the last action will send the timeline to a frame named waiting, which informs the user that the information was sent but a response has not yet been returned.

  7. Add this function definition just below the one you added in the previous step:

    function loginResponse () { var response = objToReceive.firstChild.firstChild.firstChild.nodeValue; if (response == "Login Correct") { _root.gotoAndStop("login success"); } else if (response == "Login Incorrect") { _root.gotoAndStop("login failed") } }

    This function is called as soon as the last byte of XML is loaded into the XML object called objToReceive , as shown in the previous step. It's used to parse the XML response from the server.

    The first line in this function creates a variable named response and sets its value based on the data extracted from the returned XML document. Remember that the response of the UserLogin.asp page is in this format:

    <Login> <Message>Login Correct|Login Incorrect</Message> </Login>

    As a result, response will have a value of either "Login Correct" or "Login Incorrect", depending on what's extracted from this XML document. An if statement then uses this value to send the timeline to the frame labeled either login success or login failed. This will move it from the waiting frame, which you'll remember is used as an interim location while waiting for a response from the server.

  8. Select the Submit button and add this function call:

    on (release, keyPress "<Enter>") { loginSubmit(); }

    When this button is clicked the loginSubmit() function will be called and executed. This will activate the log-in process, as described in the previous few steps.

    In summary, when the loginSubmit() function is called, XML data is sent to the server and the timeline is moved to the waiting frame. When a response is sent back from the server, the loginResponse() function is automatically called and the timeline is sent to either the frame labeled login success or that labeled login failed.

    Let's next script our project to handle the registration process.

  9. Move the playhead to the frame labeled register. At this label, you will find three text fields (userName, email, and password) and a button on the stage. With the Actions panel open, select the frame on the Actions layer at that label and add the following line of script:

    registrationURL = "http://yourdomain.com/using_xml/AddUser.asp";

    This is the ASP page that accepts the registration XML-formatted document. It will process the information and return a result. Make sure you enter the correct path to the file that you uploaded.

  10. With the same frame still selected add this function definition:

    function registrationSubmit () { xmlToSend="<Register><UserName>"+userName.text+"</UserName><Email>"+email.te xt+"</Email><Password>"+password.text+"</Password></Register>"; objToSend = new XML(xmlToSend); objToReceive = new XML(); objToReceive.onLoad = registrationResponse; objToSend.sendAndLoad(registrationURL, objToReceive); _root.gotoAndStop("waiting"); }

    The above ActionScript is similar to that used in the loginSubmit() function defined in Step 6 the only differences are in the format of the XML and some reference names. Notice that the XML document here contains three pieces of user information: userName.text , email.text , and password.text . This is the information entered into the text fields by the user. The destination script will parse this document and extract that information.

  11. Add this function definition just below the one you added in the previous step:

    function registrationResponse () { var response = objToReceive.firstChild.firstChild.firstChild.nodeValue; if (response == "User Inserted") { _root.gotoAndStop("registration success"); } else if (response == "User Exists") { _root.gotoAndStop("registration failed") } }

    This function is called when the last byte of information is loaded into objToReceive . This function is very similar to the loginResponse() function defined in Step 7. Remember that the AddUser.asp page returns a document of this format:

    <Register> <Message>User Inserted|User Exists</Message> </Register>

    As a result, response will have a value of either "User Inserted" or "User Exists" depending on what is extracted from this XML document. An if statement then uses this value to send the timeline to either the frame labeled registration success, or the frame labeled registration failed.

  12. Add this function call to the Submit button:

    on (release, keyPress "<Enter>") { registrationSubmit(); }

    When the user clicks this button or presses the Enter key, the registrationSubmit() function is called. This activates the registration process we described in the previous few steps. In summary, when the registrationSubmit() function is called, XML data is sent to the server and the timeline is moved to the waiting frame. When a response is sent back from the server, the registrationResponse() function is automatically called and the timeline is sent to either the frame labeled registration success or the one labeled registration failed.

  13. Choose Control > Test Movie to test your work. Press the Register button and then submit some information. Reopen the movie and then try to log in.

    You have just created a simple application that illustrates some uses of the XML object. Test it a few times to make sure you're comfortable with the ActionScript.

  14. Close the test movie and save your work as loginRegister2.fla

    Now you're ready to start creating some pretty advanced data-driven applications!

Категории