-
-
Save chrismanderson/d1c295de61acd67ea6a3 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
d3.jsonp.foo('Hello, World!'); |
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> | |
<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> |
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
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