I am trying to get a JSONP response from Twitter and have the following code:
<!doctype html>
<html>
<head>
</head>
<body>
<script>
(function($, container) {
container[$] = function(url){
url += '&callback=jsonp';
var scriptEl = document.createElement('script');
scriptEl.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(scriptEl);
}
window.jsonp = function(response) {
return response;
}
})('$', this);
</script>
<script>
var test = $('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=jonathonoates');
</script>
</body>
</html>
If instead of return response; in the window.jsonp function, I were to stick an alert(response) I can see that I am getting a successful response from Twitter.
I would like to return that response, as in the var test = $('http...');, but test is undefined; the response is not being returned.
I am sure I’m looking at it silly, it’s probably something to do with it being inside the closure?
I’d really appreciate you help with this!
Though, please, no jQuery etc. answers, as I’d like to learn how all this done by myself.
Thank you everyone!
Due to the behaviour of asynchronous calls, the callback function must be called after the JSONP has been retrieved from the source, in this case, Twitter.
The callback function should be passed as an argument along with the URL in the
$function so it can be called from within thejsonpfunction, that should be a child of the$function.and called like: