Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created December 18, 2010 23:13
Show Gist options
  • Save rwaldron/746957 to your computer and use it in GitHub Desktop.
Save rwaldron/746957 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<script src="jsonp.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
var requestUrl = "http://en.wikipedia.org/w/api.php?action=parse&page=Dog&format=json";
getJsonp({
url: requestUrl,
success: function( data ) {
// `data` is the parsed JSON object
console.log(data);
}
});
getJsonp({
url: requestUrl + "&callback=jsonpB",
success: function( data ) {
// `data` is the parsed JSON object
console.log(data);
}
});
getJsonp({
url: requestUrl,
jsonp: "jsonpC",
success: function( data ) {
// `data` is the parsed JSON object
console.log(data);
}
});
}, false);
</script>
</head>
<body>
</body>
</html>
// forgive me, i've polluted.
function getJsonp( setup ) {
var head = document.getElementsByTagName("head")[0] || document.documentElement,
script = document.createElement("script"),
rqstring = /\?/,
rcall = /callback/,
qstring = setup.url.split("?")[1],
params;
// if the callback was specified in the url string
if ( rcall.test( setup.url ) ) {
// break the query string
params = qstring.split("&");
// the callback argument is expected to be the last key/val pair
setup.jsonp = params[ params.length - 1 ].split("=")[1];
}
// if no setup.jsonp, create a uniquely named callback
setup.jsonp || ( setup.jsonp = "jsonp" + ( +new Date() ) );
// if no callback specified in url, add it
if ( !rcall.test( setup.url ) ) {
setup.url += ( rqstring.test( setup.url ) ? "&" : "?") + "callback=" + setup.jsonp;
}
// set the script source
script.src = setup.url;
if ( setup.jsonp ) {
// define the jsonp setup.success callback globally
window[ setup.jsonp ] = function ( data ) {
setup.success( data );
window[ setup.jsonp ].fired = true;
};
window[ setup.jsonp ].fired = false;
}
script.onload = script.onreadystatechange = function() {
if ( window[ setup.jsonp ].fired ||
( this.readyState === "loaded" || this.readyState === "complete") ) {
// cleanup in here
delete window[ setup.jsonp ];
head.removeChild( script );
}
};
head.insertBefore( script, head.firstChild );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment