public
Created

JSONP

  • Download Gist
jsonp.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/*
* usage: JSONP.get("http://gdata.youtube.com/feeds/api/videos", {q:'lindsey','max-results':3,alt:'json',v:2}, console.log);
*/
 
var JSONP = (function(){
var counter = 0;
return {
get: function (url, params, callback) {
var cid = "json_" + counter++;
var query = "?";
var scriptTag = document.createElement("script");
var key;
 
for (key in params) {
query += key + "=" + encodeURIComponent(params[key]) + "&";
}
 
window[cid] = function(){
callback.apply(null, arguments);
document.head.removeChild(scriptTag);
delete window[cid];
}
scriptTag.src = url + query + "callback=" + cid;
scriptTag.async = "async";
document.head.appendChild(scriptTag);
}
};
}());

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.