Created
April 3, 2015 07:14
-
-
Save cowsrule/c4bc5c8a35f497ed5677 to your computer and use it in GitHub Desktop.
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
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