Created
August 26, 2012 08:43
-
-
Save marcus-at-localhost/3476295 to your computer and use it in GitHub Desktop.
Crossdomain JSONP request via YQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var url_str = 'http://www.google.com/ig/api?weather=Berlin+Germany&hl=de'; | |
requestCrossDomain(url_str, function(json) { | |
// check the real output at YQL console | |
// http://goo.gl/Z9XHu | |
console.log(json.xml_api_reply.weather) | |
}); | |
// Accepts a url and a callback function to run. | |
// returns jsonp | |
function requestCrossDomain( site, callback ) { | |
// If no url was passed, exit. | |
if ( !site ) { | |
alert('No site was passed.'); | |
return false; | |
} | |
// Take the provided url, and add it to a YQL query. Make sure you encode it! | |
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=json&callback=?'; | |
// Request that YSQL string, and run a callback function. | |
// Pass a defined function to prevent cache-busting. | |
$.getJSON( yql, cbFunc ); | |
function cbFunc(data) { | |
// If we have something to work with... | |
if (data.query.results !== null) { | |
data = data.query.results; | |
// If the user passed a callback, and it | |
// is a function, call it, and send through the data var. | |
if ( typeof callback === 'function') { | |
callback(data); | |
} | |
} | |
// Else, Maybe we requested a site that doesn't exist, and nothing returned. | |
else throw new Error('Nothing returned from getJSON.'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment