开发者

JSON parser doesn't work

开发者 https://www.devze.com 2023-01-07 17:19 出处:网络
For some reason my json twitter parser isn\'t working? Anyone got any ideas as to why? <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\">

For some reason my json twitter parser isn't working?

Anyone got any ideas as to why?

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script type="text/javascript">

    function outputHtmlToDiv(tweet,i){
      count = i + 1;
      $('#wrapper #sidebar .profile').html('<img src="'+tweet.profile_image_url+'" alt="Pretty Klicks" />');
    }
        $(document).ready(function(){

        var url = 'http://twitter.com/s开发者_StackOverflow中文版tatuses/user_timeline/prettyklicks.json?count=1';

            $.getJSON(url,function(json){
                $.each(json.user,function(i,tweet){
                  outputHtmlToDiv(tweet,i);
                });
              });

        });


</script>


You have a few errors, mainly you need &callback=? in the url, like this:

 var url = 'http://twitter.com/statuses/user_timeline/prettyklicks.json?count=1&callback=?';

Otherwise jQuery doesn't know to make a JSONP request (a normal XHR request is blocked cross-domain, complements of the same-origin policy). Also your get structure's a bit off, the base object is an array, overall it should look like this:

function outputHtmlToDiv(tweet, i) {
  count = i + 1;
  $('#wrapper #sidebar .profile').html('<img src="'+tweet.user.profile_image_url+'" alt="Pretty Klicks" />');
}
$(function(){
  var url = 'http://twitter.com/statuses/user_timeline/prettyklicks.json?count=1&callback=?';
  $.getJSON(url,function(json){
    $.each(json,function(i,tweet){
      outputHtmlToDiv(tweet,i);
    });
  });
});​

You can test it out here, since json in the object above is an array of tweets, you need to loop through that array directly, json.user will be undefined (Array doesn't have a property called users), json[0].user however, is what you want.


Missing quote after '+tweet.profile_image_url+'

Try this:

$('#wrapper #sidebar .profile').html('<img src="'+tweet.profile_image_url+'" alt="Pretty Klicks" />');


Is that because you have unclosed quote after img/src?

Intead of:

$('#wrapper #sidebar .profile').html('<img src="'+tweet.profile_image_url+' alt="Pretty Klicks" />');

Try:

$('#wrapper #sidebar .profile').html('<img src="'+tweet.profile_image_url+'" alt="Pretty Klicks" />');


You need to use a JSONP callback parameter (see the documentation). With jQuery, you can just use a ? and it will generate a name:

var url = 'http://twitter.com/statuses/user_timeline/prettyklicks.json?count=1&callback=?';
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号