-
-
Save ilovejs/1f320127a20694e41c74 to your computer and use it in GitHub Desktop.
This file contains 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
<!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> |
This file contains 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 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
http://ains.co/blog/things-which-arent-magic-jsonp.html