Skip to content

Instantly share code, notes, and snippets.

@erjjones
Forked from sindresorhus/jsonp-usage.js
Created March 7, 2012 21:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save erjjones/1996286 to your computer and use it in GitHub Desktop.
Save erjjones/1996286 to your computer and use it in GitHub Desktop.
JSONP function - Easily fetch remote JSONP files
// Example usage: Fetch it's own code from GitHub
JSONP( 'https://api.github.com/users/erjjones?callback=?', function( response ) {
var data = response.data;
console.log(data.followers);
});
function JSONP( url, callback ) {
var id = ( 'jsonp' + Math.random() * new Date() ).replace('.', '');
var script = document.createElement('script');
script.src = url.replace( 'callback=?', 'callback=' + id );
document.body.appendChild( script );
window[ id ] = function( data ) {
if (callback) {
callback( data );
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment