106 | Chapter 4: AIR Mini-Cookbook
Once we have specified these arguments in the open method,
we will call the send method. Thesendmethod takes a single
argument that contains the content that is to be sent with the
request. In our case, we won’t send any data with the
request:
var xml = new XMLHttpRequest( );
xml.open( "GET", "http://www.foo.com/data.xml", true );
xml.send( null );
Because we are loading the data asynchronously, we need to
create a handler for the response which is called once the
data has loaded from the server. This handler will be added
before the send method is called. Within this handler we will
save the data that is located in theresponseTextproperty of
theXMLHttpRequestinstance to a known location on the local
file system for retrieval in subsequent requests. Reading and
writing text to the local system is covered elsewhere in the
book, and therefore we won’t cover it in detail here:
xml.onreadystatechange = function( )
{
if( xml.readyState == 4 ) // the request is complete
{
// write the data to the local system
var file =
air.File.applicationStorageDirectory.resolve("data.xml");
var fileStream = new air.FileStream( );
fileStream.open( file, air.FileMode.WRITE );
fileStream.writeMultiByte( xml.responseText ,
air.File.systemCharset );
fileStream.close( );
}
}
Before each request of the data we will need to check if the
data.xmlfile exists. If it exists, we do not need to load the file
using theXMLHttpRequestobject and can use the File API to
load it from the disk. This allows us to load the data even if
the user is not currently online:
var data = null;
var file = air.File.applicationStorageDirectory.
resolve("data.xml");