Skip to content

Instantly share code, notes, and snippets.

@tobi
Created July 9, 2011 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobi/1073641 to your computer and use it in GitHub Desktop.
Save tobi/1073641 to your computer and use it in GitHub Desktop.
jsonp mini implementation
<!DOCTYPE HTML>
<html>
<head>
<title>MINI JSONp</title>
</head>
<body>
<script>
var uniqueId = function(chars) {
var chars = (chars || 16), result = '';
while (--chars) { result += (Math.random()*16|0).toString(16) }
return result;
};
var jsonp = function(url, callback) {
// this shows dynamic script insertion
var funcName = 'callback' + uniqueId();
var script = document.createElement('script');
url = url + (/\?/.test(url) ? '&' : '?') + "callback=" + funcName;
script.setAttribute('src', url);
var elem = document.getElementsByTagName('head')[0].appendChild(script);
window[funcName] = function() {
callback(arguments[0])
// cleanup
elem.parentNode.removeChild(elem);
delete window[funcName];
}
}
var tweet = function(t) {
console.log(t.user.screen_name + ": " + t.text + '<br>' )
}
jsonp("http://twitter.com/status/user_timeline/tobi.json?count=10", function(result){
result.forEach(tweet)
})
jsonp("http://twitter.com/status/user_timeline/shopify.json?count=10", function(result){
result.forEach(tweet)
})
</script>
dasdsa
</body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment