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);
});
});
Because of cross domain security policies.
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 thesrcset 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&callback=foo. The remote server response is formulated asfoo({ 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.