I wrote this a while back when I needed to do pseudo AJAX calls to a remote host. Due to XSS restrictions and security policies, a normal XMLHttpRequest (XHR) call is not allowed to work across domains or even sub-domains. But Yahoo’s YQL interface kindly lets you GET any URL (which also means being able to submit via GET), irregardless of whether the domain is local or not.
Here is how it works. You need mootools (also download mootools-more as this class will extend Request.JSONP which is a part of mootools-more).
Request.YQLajax = new Class({ // gets basic info such as country and latitude data Extends: Request.JSONP, options: { log: !true, url: 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22{location}%22&format=xml' }, initialize: function(location, options) { this.parent(options); if (!location) return; this.options.url = this.options.url.substitute({location: encodeURIComponent(location)}); } }); // example use to fetch BBC's page new Request.YQLajax("http://www.bbc.co.uk/", { onSuccess: function(data) { document.id('result').set('html', data.results); } }).send();
You can see this in action on http://jsfiddle.net/dimitar/wxmXq/ or play with it below. Happy cross-domain ajax-ing.
[…] Cross-domain AJAX calls via YQL as proxy and mootools JSONP | frag … tags: figure-out, from-the-way, interface-kindly, means-being, not-allowed, […]
thanks to Fabio for the tip on embedding the mooshell into the post.
[…] Read more from the example source: Cross-domain AJAX calls via YQL as agent and mootools JSONP | frag … […]