Cross-Site XMLHttpRequest
I've just finished writing up some docs on the new Cross-Site XMLHttpRequest feature in Firefox 3. I was a little worried at first, but it definitely appears to be both easy-to-implement and easy-to-use. Specifically, it's an implementation of the W3C Access Control working draft (which is respected by Firefox's XMLHttpRequest).
If you're interested in giving it a try you should fire up your copy of Firefox 3 and get ready to take it for a spin.
In a nutshell, there are two techniques that you can use to achieve your desired cross-site-request result: Specifying a special Access-Control header for your content or including an access-control processing instruction in your XML.
More information can be found in the documentation but here's a quick peek at what your code might look like:
An HTML document (served via PHP) that specifies an Access-Control header: (Demo - FF3 Only)
// Change this to allow <yourdomain.com> to make it accessible to your site, or allow <*> for ANYONE to be able to access it.
header('Access-Control: allow <ejohn.org>');
?>
<b>John Resig</b>
An XML document that specifies an access-control processing instruction: (Demo - FF3 Only)
<!-- Change this to allow="yourdomain.com" to make it accessible to your site, or allow="*" for ANYONE to be able to access it. -->
<?access-control allow="ejohn.org"?>
<simple><name>John Resig</name></simple>
Now what's especially nice about all this is that you don't have to change a single line of your client-side code to make this work! Take, for example, this page which requests an HTML file from a remote domain - and, specifically, the JavaScript within it:
xhr.open("GET", "http://dev.jquery.com/~john/xdomain/test.php", true);
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
document.body.innerHTML = "My Name is: " + xhr.responseText;
} else {
document.body.innerHTML = "ERROR";
}
}
};
xhr.send(null);
This is same-old pure-blood JavaScript/DOM/XMLHttpRequest, as we're use to it. For some limited applications, I think this functionality is already going to be terribly useful - and once wider adoption starts to trickle in we can certainly see a whole range of applications, especially in the area of client-side applications and mashups.
Tags: xmlhttprequest, mozilla, ajax, firefox
27 Comments on 'Cross-Site XMLHttpRequest'



