Wednesday, February 15th, 2006
Cross-Domain XML
<p>Like it or not, there's plenty of people who want to do cross-domain remoting. The typical technique is via script tags, and since this means the response must be valid Javascript, JSON is usually the message format. But what if you want to grab some XML instead of a JSON-formatted object? Dave Johnson explains how to achieve cross-domain XML, building on the standard script tag trick.The server responds with a script that includes the XML string, along with some code to convert it to a DOM object ... as Dave's code shows, XMLHttpRequest is not the only way to make such a conversion:
-
-
var eba_ajax_xmlp = {x: {}};
-
eba_ajax_xmlp.loadXml = function(s, uid){
-
if(document.implementation && document.implementation.createDocument) {
-
var objDOMParser = new DOMParser();
-
this.x[uid] = objDOMParser.parseFromString(s, "text/xml");
-
} else if (window.ActiveXObject) {
-
this.x[uid] = new ActiveXObject('MSXML2.DOMDocument.3.0');
-
this.x[uid].async = false;
-
this.x[uid].loadXML(s);
-
}
-
}
-
If it's a DOM object you're after, I guess there's an alternative strategy here too: pull down a JSON-formatted DOM object.
Related Content:











Michael,
a bit off topic, but I’m so curious. How do you syntax highlight the JavaScript code? From the source it looks like some kind of preprocessed code?
Jesper, it’s a syntax highlighting module for WordPress. Dion set it up, so I’m not sure which name, but I just mark up as [javascript]..[/javascript] or [php]…[/php] etc. As it happens, good old Vim is also capable of HTMLizing its syntax highlighting. (In vim, type “:help 2html” for more info).
If I understand correctly, if a service provider wanted to enable oters to be able to use the service, he could post the JavaScript file to his own server and then developers could “include” his code via and the code in that script would be able to call that server which is different from the server which served the html?
Great tip, Michael. Thanks!
The vim tip works wonderfully! Thanks Michael.
pwb, yes that’s correct. As long as it’s valid Javascript, a page can dynamically point a script tag to it, which will lead to that remote Javascript being executed in the browser. The JS can be sitting anywhere on the web.
But then can that JavaScript call the server it came from?
I’m doing this in testing at http://blog.quimble.com – If anyone has a few minutes – I’d be happy to share my experience in exchange for a little knowledge. It seems that firefox grants access to cookies on the remote site, but IE does not. Anyone have any similar situations?
Great article. I appreciate the info.
hey Topper, yes this script is NOT WORKING on IE.
very bad :(