Let's return to our quiz game from Chapter 8 and upgrade it with the lessons from Chapter 9. Then it will be ready to interface with the PHP code we just wrote. We start with the original contents of Frame 1 ”a hardcoded database ”and replace all the literal definitions of Questions and Answers with downloaded XML data. ActionScriptfunction Question( questiontext, answerarray ){ this.q= questiontext; this.a= answerarray; } function Answer( text, score, comment ){ this.text=text; this.score=score; this.comment=comment; } whichquestion=1; quiz = new Array(); xml=new XML(); xml.trace = function() { for( var i=0 ; i<this.childNodes.length; i++){ this.childNodes[i].trace = this.trace; this.childNodes[i].trace(); } Unlike earlier versions of this recursive function, this one recurses first, then analyzes the current node. The advantage is that we discover the element as we are closing it, and all the data subelements it requires ( Questions need Answers and Answers need Comments ) have already been encountered and are ready to use. ActionScriptif( this.nodeName eq "Comment" ) newComment = getText(this); A Comment simply grabs its text nodes. ActionScriptif( this.nodeName eq "Answer" ){ newScore= this.attributes["score"]; if(!newAnswerArray) newAnswerArray=new Array(); newAnswerArray.push( new Answer( getText(this), newScore, newComment)); delete( newComment) ; } An Answer assembles its own text, its score attribute, and any existing Comment. After making sure that there is an array into which it can place this Answer, it calls the Answer constructor with all the data and the stuffs the object produces into the array. It then destroys the Comment so that the next Answer starts with a blank. ActionScriptif( this.nodeName eq "Question" ){ quiz.push( new Question(getText(this), newAnswerArray) ); delete( newAnswerArray ); } } Finally the Question object combines its own text with the array of Answers and calls the Question constructor. The Question is added to the Quiz. ActionScriptfunction getText( node ) { text=""; for( var i=0; i<node.childNodes.length; i++) if( node.childNodes[i].nodeType==3 ) text+= node.childNodes[i].nodeValue; return text; } xml.cleanse= function () The body of this function (which cleans out white space) is omitted for brevity. It can be found in earlier chapters. ActionScriptxml.onLoad = function ( ok ) { if( !ok ) statusline = "XML Load failure"; else{ this.cleanse(); this.trace(); _root.nextFrame(); } } Of interest is the last line of the onLoad handler. NextFrame() occurs when the load is succesful. However even though this code is written in the _root level and executes (like all object code) in the _root context, it does not suffice to call nextFrame() without specifying the context. ActionScriptxml.load("quiz.php"); stop(); When it calls the PHP code, the result is lovely (Figure 10.3). Figure 10.3. Quiz Data Downloaded from a PHP Server Script
|