Created
February 24, 2012 12:38
-
-
Save sindresorhus/1900694 to your computer and use it in GitHub Desktop.
JSONP function - Easily fetch remote JSONP files
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
// Example usage: Fetch it's own code from GitHub | |
JSONP( 'https://api.github.com/gists/1900694?callback=?', function( response ) { | |
console.log( 'JSONP function:', response.data.files['jsonp.js'].content ); | |
}); |
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
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