AJAX - The Complete Reference

(avery) #1

PART III


Chapter 10: Web Services and Beyond 497


environment complete with a number of useful communication features. For example, in
ActionScript you can load a document from a remote resource very quickly.

var myXML = new XML();
myXML.load(url); /* url contains the address we want to load */

However, don’t get too excited about breaking free of the same origin restriction; Flash
has calling restrictions as well. You can certainly try to put an arbitrary URL in this method,
but the Flash Player will first fetch a file from the root of the domain called crossdomain.
xml. This file sets up the access policy for remote requests from Flash. For example,
http://unsecure.ajaxref.com/crossdomain.xml exists and contains the following rules:

<cross-domain-policy>
<allow-access-from domain="ajaxref.com" to-ports="*"/>
<allow-access-from domain="*.ajaxref.com" to-ports="*"/>
</cross-domain-policy>

This file indicates that other requests from ajaxref.com subdomains can make
connections remotely.
The syntax for crossdomain.xml files is quite basic. You have the primary tag <cross-
domain-policy> that includes <allow-access-from> tags. These tags have a domain
attribute that is a full domain (for example, http://www.ajaxref.com), partial wild-card domain
(for example, *.ajaxref.com), or full wildcard (*). The secure attribute should be set to true; if
set to false, it allows Flash movies served via HTTP to attach to https URLs. The complete
DTD for the crossdomain.xml format is shown here:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!ELEMENT cross-domain-policy (allow-access-from*)>
<!ELEMENT allow-access-from EMPTY>
<!ATTLIST allow-access-from domain CDATA #REQUIRED>
<!ATTLIST allow-access-from secure (true|false) "true">

As we remember, the same origin policy is quite restrictive, and we can’t even connect
from http://www.ajaxref.com to unsecure.ajaxref.com with an XHR. With Flash we will be able to
do it as long as we have a valid crossdomain.xml on the site we are trying to call, but how
does this help us since it requires Flash to be used? It turns out we can bridge calls from
JavaScript into a Flash SWF file and back again. Read over the following ActionScript file
(ajaxtcrflash.as):

import flash.external.ExternalInterface;
class AjaxTCRFlash{
static function connect(url, callback)
{
var myXML = new XML();
myXML.ignoreWhite = true;
myXML.onLoad = function(success)
{
if (success) {
ExternalInterface.call(callback, this.toString());
}
};
Free download pdf