Created
January 9, 2013 16:50
-
-
Save tmcw/4494715 to your computer and use it in GitHub Desktop.
d3 jsonp plugin
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('foo.jsonp?callback=d3.jsonp.foo', function(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=d3.jsonp.(\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