Skip to content

Instantly share code, notes, and snippets.

@fhefh2015
Forked from erjjones/jsonp-usage.js
Created September 26, 2016 06:00
Show Gist options
  • Save fhefh2015/bcf71f5351682de124e27cd4557c1aaf to your computer and use it in GitHub Desktop.
Save fhefh2015/bcf71f5351682de124e27cd4557c1aaf 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