Skip to content

Instantly share code, notes, and snippets.

@indianajone
Created July 25, 2018 03:35
Show Gist options
  • Save indianajone/f0d87f77d8127bfc16f59ccd9ce92929 to your computer and use it in GitHub Desktop.
Save indianajone/f0d87f77d8127bfc16f59ccd9ce92929 to your computer and use it in GitHub Desktop.
Useful jsonp method
function jsonp(url, callback) {
var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
window[callbackName] = function (data) {
delete window[callbackName];
document.body.removeChild(script);
callback(data);
};
var script = document.createElement('script');
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
script.onerror = function (err) {
console.error(err);
}
document.body.appendChild(script);
}
jsonp('__URL__', function (data) {
console.log(data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment