Skip to content

Instantly share code, notes, and snippets.

@chrismanderson
Forked from tmcw/foo.jsonp
Last active August 29, 2015 14:09
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 chrismanderson/d1c295de61acd67ea6a3 to your computer and use it in GitHub Desktop.
Save chrismanderson/d1c295de61acd67ea6a3 to your computer and use it in GitHub Desktop.
d3.jsonp.foo('Hello, World!');
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font:12px/20px 'Helvetica';
}
textarea, input {
width:100%;
height:20px;
margin:0;
padding:0;
}
</style>
<body>
<h1>
</h1>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="jsonp.js"></script>
<script>
d3.jsonp('http://elections.huffingtonpost.com/pollster/api/charts?callback=pollsterCallback&topic=2016-president-gop-primary&state=US', function(d) {
pollsterCallback(d);
console.log(d);
d3.select('h1').text(d);
});
</script>
d3.jsonp = function (url, callback) {
function rand() {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
c = '', i = -1;
while (++i < 15) c += chars.charAt(Math.floor(Math.random() * 52));
return c;
}
function create(url) {
var e = url.match(/callback=(\w+)/),
c = e ? e[1] : rand();
d3.jsonp[c] = function(data) {
callback(data);
delete d3.jsonp[c];
script.remove();
};
return 'd3.jsonp.' + c;
}
var cb = create(url),
script = d3.select('head')
.append('script')
.attr('type', 'text/javascript')
.attr('src', url.replace(/(\{|%7B)callback(\{|%7D)/, cb));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment