Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code for "Things Which Aren't Magic - JSONP"
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
<script type="text/javascript" src="jsonp.js"></script>
<script>
var addParagraph = function(text) {
var p = document.createElement('p');
p.textContent = text;
document.body.appendChild(p);
};
var API_URL = "https://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=?";
JSONP.fetch(API_URL, function (res) {
addParagraph(res.title)
res.items.forEach(function (item) {
addParagraph(item.link);
});
});
</script>
</html>
var JSONP = function () {
return {
fetch: function (url, cb) {
// Generate a random function name
var cbName = "cb" + Math.floor(Math.random() * 1000);
// Define global callback function
window[cbName] = function(payload) {
// Call the users callback w/ payload
cb(payload);
// Clean up this function when we're done;
delete window[cbName];
};
// Replace "callback=?" with actual callback function name
var scriptUrl = url.replace("callback=?", "callback=" + cbName);
// Inject script tag
var scriptElem = document.createElement("script");
scriptElem.setAttribute('src', scriptUrl);
document.body.appendChild(scriptElem);
}
};
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment