Skip to content

Instantly share code, notes, and snippets.

@nanha
Created May 26, 2011 04:53
Show Gist options
  • Save nanha/992575 to your computer and use it in GitHub Desktop.
Save nanha/992575 to your computer and use it in GitHub Desktop.
JSONp using closure
var jsonp = {
callbackCounter: 0,
fetch: function(url, callback) {
var fn = 'JSONPCallback_' + this.callbackCounter++;
window[fn] = this.evalJSONP(callback);
url = url.replace('=JSONPCallback', '=' + fn);
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = url;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
},
evalJSONP: function(callback) {
// eval이 아닌 JSON object 를 사용하도록 조치하기 위한 closure 도입.
return function(data) {
var validJSON = false;
if (typeof data == "string") {
try {
validJSON = JSON.parse(data);
} catch (e) {
/*invalid JSON*/
}
} else {
validJSON = JSON.parse(JSON.stringify(data));
window.console && console.warn('not valid JSON string');
}
if (validJSON) {
callback(validJSON);
} else {
throw("not valid json");
}
};
}
}
// 사용예제
/*
var obamaTweets = "http://www.twitter.com/status/user_timeline/BARACKOBAMA.json?count=5&callback=JSONPCallback";
jsonp.fetch(obamaTweets, function(data) {console.log(data[0].text)});
var reddits = "http://www.reddit.com/.json?limit=1&jsonp=JSONPCallback";
jsonp.fetch(reddits , function(data) {console.log(data.data.children[0].data.title)});
*/
@nanha
Copy link
Author

nanha commented Nov 9, 2011

oh. thanks. miss that

@sindhusp
Copy link

sindhusp commented Jan 2, 2013

Thanks for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment