can't get the twitter status updates from jQuery
why is the code below showing 'got the result null' alertbox ? while t开发者_开发技巧he 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.
$(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&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.
精彩评论