Skip to content

Instantly share code, notes, and snippets.

@ains
Created March 31, 2015 13:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ains/e127290195a5e4e304d3 to your computer and use it in GitHub Desktop.
Save ains/e127290195a5e4e304d3 to your computer and use it in GitHub Desktop.
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