Erik's blog

Code, notes, recipes, general musings

playing with e4x in firefox: asynchronously loading arbitrary xml as an e4x-ready object

leave a comment »

<script>
/*
ref: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Processing_XML_with_E4X
ref: http://bit.ly/IbKMB
prereq: firefox w/ firebug installed and a server running php w/ simplexml
note: i'm using a server-side proxy so we can easily make requests to an arbitrary domain
usage:
1) put this code in an php file called 'proxy.php' (or whatever, but make sure the url in the javascript matches)
2) upload this file to your server
3) run it in firefox
4) look for output in console
*/

<?php if($_GET&#91;'run'&#93;){//wait to run until javascript loads and recursively makes a request to this file
	$url = 'http://query.yahooapis.com/v1/public/yql?q=show%20tables&format=xml';//arbitrary xml
	$sxml = simplexml_load_file($url);//just an easy way to request xml
    //strip off the xml declaration because the javascript XML() object expects raw xml
	echo str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $sxml->asXML());
}else{//on initial load, output the html/javascript
?>

<script>
var callback = function (text) {
		var xml = new XML(text);//convert text to an e4x-ready xml object
		console.log(xml);
	},
	url = 'proxy.php?run=true',
	req = new XMLHttpRequest();

req.open('GET', url, true);
req.onreadystatechange = function () {
	if (req.readyState == 4 && req.status == 200) {
		callback(req.responseText);//load up xml from proxy as text
	}
};
req.send(null);
</script>

<?php
}
?>
Advertisements

Written by Erik

May 21, 2009 at 9:50 pm

Posted in code, tutorial

Tagged with , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: