Skip to content

Instantly share code, notes, and snippets.

@icodeforlove
Created December 4, 2011 23:17
Show Gist options
  • Save icodeforlove/1431613 to your computer and use it in GitHub Desktop.
Save icodeforlove/1431613 to your computer and use it in GitHub Desktop.
simple JSONP support
/**
* simple JSONP support
*
* JSONP.get('https://api.github.com/gists/1431613', function (data) { console.log(data); });
* JSONP.get('https://api.github.com/gists/1431613', {}, function (data) { console.log(data); });
*
* gist: https://gist.github.com/gists/1431613
*/
var JSONP = (function (document) {
var requests = 0,
callbacks = {};
return {
/**
* makes a JSONP request
*
* @param {String} src
* @param {Object} data
* @param {Function} callback
*/
get: function (src, data, callback) {
// check if data was passed
if (!arguments[2]) {
callback = arguments[1];
data = {};
}
// determine if there already are params
src += (src.indexOf('?')+1 ? '&' : '?');
var head = document.getElementsByTagName('head')[0],
script = document.createElement('script'),
params = [],
requestId = requests,
param;
// increment the requests
requests++;
// create external callback name
data.callback = 'JSONP.callbacks.request_' + requestId;
// set callback function
callbacks['request_' + requestId] = function (data) {
// clean up
head.removeChild(script);
delete callbacks['request_' + requestId];
// fire callback
callback(data);
};
// traverse data
for (param in data) {
params.push(param + '=' + encodeURIComponent(data[param]));
}
// generate params
src += params.join('&');
// set script attributes
script.type = 'text/javascript';
script.src = src;
// add to the DOM
head.appendChild(script);
},
/**
* keeps a public reference of the callbacks object
*/
callbacks: callbacks
};
})(document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment