Skip to content

Instantly share code, notes, and snippets.

@cowsrule
Created April 3, 2015 07:14
Show Gist options
  • Save cowsrule/c4bc5c8a35f497ed5677 to your computer and use it in GitHub Desktop.
Save cowsrule/c4bc5c8a35f497ed5677 to your computer and use it in GitHub Desktop.
self.JSONP = function (params)//(url, data, method, callback)
{
self.Assert(params.url, 'Must supply a valid URL to fetch');
self.Assert(params.cb, 'Must supply a valid callback');
var url = params.url;
var data = params.data;
var cb = params.cb;
if (data)
{
var queryString = '';
var keys = Object.keys(data);
for (var i = 0; i < keys.length; i++)
{
queryString += encodeURIComponent(keys[i]) + '=' + encodeURIComponent(data[keys[i]]);
if (i !== keys.length - 1)
{
queryString += '&';
}
}
url += '?' + queryString;
}
var timestamp = Date.now();
var generatedFunction = 'jsonp' + Math.round(timestamp + Math.random() * 10001);
window[generatedFunction] = function (json)
{
cb(json);
delete window[generatedFunction];
};
if (url.indexOf('?') === -1) { url = url+'?'; }
else { url = url+'&'; }
var jsonpScript = document.createElement('script');
jsonpScript.id = generatedFunction;
jsonpScript.setAttribute('src', url + 'callback=' + generatedFunction);
document.getElementsByTagName('head')[0].appendChild(jsonpScript);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment