views:

32

answers:

1

why is the code below showing 'got the result null' alertbox ? while the request seems to be sending a proper json.

 $(function(){
       $.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=twitterusername', function(data) {
        alert('got the result '+data);
        });
       });
A: 

Because of cross domain security policies.

 $(function(){ 
       $.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=twitterusername&callback=?', function(data) { 
        alert('got the result '+data); 
        }); 
       }); 

http://www.jsfiddle.net/yewVa/

Note the addition of callback=? to the URL. Note that the server must support JSONP responses for this to work.

See http://api.jquery.com/jQuery.getJson/ for more details on both of these.

JSONP requires the website from which you're pulling the data off to understand JSONP, rather than the website it's running on. JSONP works by injecting <script> tags into your document, with the src set as the remote document.

JSONP relies on the remote document wrapping it's response in the name of the function specified in the callback (jQuery masks this from you, which is why you only see a "?" as the callback parameter. After jQuery has finished fiddling, the URL ends up as http://somewhere.com/?someparam=4&amp;callback=foo. The remote server response is formulated as foo({ someparam:4} ), which is parsed as JavaScript as it's been loaded into a <script> tag.

Note that because of this approach, there is little possiblity of handling errors.

Matt
does cross domain security mean that i won't be able to use the above in a widget for my blog with blogger ?
Bunny Rabbit
@Bunny: You should be able to use it. I've also expanded my answer.
Matt