Article Written

  • on 08.03.2009
  • at 01:33 PM
  • by admin
Mar8

Crossword Web App, Part 5 0 Comments

When I first started developing this crossword tutorial, I wanted the end game to access USA Today’s crossword XML feed directly and offer a new game each day. Sadly, their feed is secured. Although I can track it down, view its source in a Web browser, save to a local file and upload to my server, I cannot get my code to access the file directly from their server. Keep that in mind when we reach the end of this tutorial. You’ll be able to play one completed game, but don’t get too attached. There’s not much replayability.

Part 5: Importing From XML

Most programs, including games, require data. More often than not this data must be updated regularly so as to sustain the usefulness of the application. This type of data is usually stored externally (out of the application’s main code) since it makes very little sense to require the application’s user to download a new version of the program every day in order to receive the latest and greatest data. Therefore, with respect to our game, it makes a great deal of sense to store the data for each crossword puzzle in an external XML file. This way each puzzle can easily be loaded individually by referencing a different XML file.

To import data from an XML file, we use the XMLHttpRequest Javascript object as follows.

var url = 'xml/070814.xml';var xmlhttp = new XMLHttpRequest();  if (xmlhttp != null) {xmlhttp.onreadystatechange = stateChange;xmlhttp.open('GET', url, true);xmlhttp.send(null);} else {alert('Your browser does not support XMLHTTP.'); }} function stateChange() {if (xmlhttp.readyState == 4) {if (xmlhttp.status == 200) {/*A status of 200 means that the XML file wasloaded and parsed without error. At this pointyou'll want to sort through all of the data sothat it can be used by your program. I'll giveyou some tips on how to do this in the nextupdate.*/} else {alert('Problem retrieving XML data.');}}}

Figure 1. Using XMLHttpRequest to load and read an XML file

We’ll talk more about reading from XML files in the next update.

—Ryan