Created
September 26, 2017 18:39
-
-
Save szanata/ca1de1038b53dd02aaa651152300ad8f to your computer and use it in GitHub Desktop.
Get jsonp
This file contains hidden or 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
function serialize(obj, prefix) { | |
var props = []; | |
for (var p in obj){ | |
if (obj.hasOwnProperty(p)) { | |
if (Object.prototype.toString.call(obj[p]) === '[object Object]'){ | |
props.push(serialize(obj[p], (prefix ? prefix : '') + p + '.')); | |
}else{ | |
props.push((prefix ? prefix : '') + encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])); | |
} | |
} | |
} | |
return props.join('&'); | |
} | |
function getJsonp(path, data, callback, parser) { | |
var id = new Date().getTime(), | |
callbackFuncName = 'jsonpCallback' + id, | |
script = document.createElement('script'), | |
timeOutMonitor; | |
window[callbackFuncName] = function (data, status, statusText) { | |
clearTimeout(timeOutMonitor); | |
callback(parser ? parser(data) : data); | |
delete window[callbackFuncName]; | |
var s = document.getElementById(id); | |
s.parentNode.removeChild(s); | |
} | |
if (data){path += (path.indexOf('?') > -1 ? '&' : '?') + serialize(data);} | |
path = path + (path.indexOf('?') > -1 ? '&' : '?') + 'callback=' + callbackFuncName; | |
timeOutMonitor = setTimeout(function (){ | |
console.error('>>> ERROR JSONP on URL: ' + path + ' > STATUS: (send timeout)'); | |
callback(null, {code: 0, message: 'Timeout error'}); | |
delete window[callbackFuncName]; | |
var s = document.getElementById(id); | |
s.parentNode.removeChild(s); | |
}, 30000); | |
script.id = id; | |
script.src = path; | |
document.getElementsByTagName('head')[0].appendChild(script); | |
} | |
getJsonp( | |
'https://itunes.apple.com/search', | |
{term:'Michel Telo Humilde Residencia', country:'BR', media:'music', entity:'musicTrack'}, | |
function (d) { | |
console.log(d); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment