Created
September 15, 2013 14:03
-
-
Save seykron/6571021 to your computer and use it in GitHub Desktop.
Simple JSONP request example.
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 addScript = function (url) { | |
var script = document.createElement("SCRIPT"); | |
var parentNode = document.getElementsByTagName("HEAD")[0]; | |
script.async = true; | |
script.type = "text/javascript"; | |
script.src = url; | |
script.addEventListener("load", function () { | |
parentNode.removeChild(script); | |
}); | |
parentNode.appendChild(script); | |
}; | |
var jsonpRequest = function (url, callback) { | |
var callbackName = "jsonp_callback_" + | |
Math.floor(Date.now() * Math.random()); | |
var requestUrl = url + "?callback=" + callbackName; | |
window[callbackName] = function (response) { | |
delete window[callbackName]; | |
callback(response); | |
}; | |
addScript(requestUrl); | |
}; | |
var JSONP_URL = "https://api.github.com/users/seykron/repos"; | |
jsonpRequest(JSONP_URL, function (result) { | |
console.log(result); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment