Skip to content

Instantly share code, notes, and snippets.

@szanata
Last active August 29, 2015 14:09
Show Gist options
  • Save szanata/3ebef8b6421f0f722050 to your computer and use it in GitHub Desktop.
Save szanata/3ebef8b6421f0f722050 to your computer and use it in GitHub Desktop.
Get jsonp
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