Created
May 26, 2011 04:53
-
-
Save nanha/992575 to your computer and use it in GitHub Desktop.
JSONp using closure
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
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)}); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
oh. thanks. miss that