简体   繁体   中英

Listing all posts with Blogger API

I'm trying to list all blog posts with the Blogger API v3:

<script type="text/javascript">
function handleResponse(response) {
  var post_number  = Object.keys(response.items).length; //number of posts
  for (i=0; i<post_number; i++) {
    $('#content').append('<div id="post' + (i+1) + '" class="post"><p></p></div>');
    $('.post p').html(Object.keys(response.items[i].title));
  }
}
</script>
<script src="https://www.googleapis.com/blogger/v3/blogs/1961645108677548855/posts?callback=handleResponse&key=AIzaSyAJESQB3ddltUcDbZif3LUnX-Gzr18tBRg"></script>

This does append 3 divs (because of 3 posts) to my content div. But the content of each of this divs is:

<p>
   "1"
   "2"
   "3"
   "4"
   "5"
</p>

I have no clue why, though I assume that title is an attribute of items[] . Any solutions or clues?

Thanks for answers!

You should removed Object.keys() and try this:

<script type="text/javascript">
function handleResponse(response) {
  var post_number  = Object.keys(response.items).length; //number of posts
  for (i=0; i<post_number; i++) {
    $('#content').append('<div id="post' + (i+1) + '" class="post"><p></p></div>');
    $('.post p').html(response.items[i].title);
  }
}
</script>
<script src="https://www.googleapis.com/blogger/v3/blogs/1961645108677548855/posts?callback=handleResponse&key=AIzaSyAJESQB3ddltUcDbZif3LUnX-Gzr18tBRg"></script>

In you case you shouldn't use Object.keys()

You request doesn't use the maxResults parameter and limited number of posts is retrieved so I recommend to use Google JavaScript Client Library - Blogger API and recursively retrieve all posts of a blog.

See the following example:

  <script>
  function renderResults(response) {
    if (response.items) {
      for (var i = 0; i < response.items.length; i++) {
        //do whatever you want with the posts of your blog
      }      
    }
    if(response.nextPageToken) {
      var blogId = 'XXX Your blogId XXX';
      var request = gapi.client.blogger.posts.list({
        'blogId': blogId,
        'pageToken': response.nextPageToken,
        'maxResults': 100,
      });
      request.execute(renderResults);
    }
  }
  function init() {
    gapi.client.setApiKey('XXX Get your API Key from https://code.google.com/apis/console XXX');
    gapi.client.load('blogger', 'v3', function() {
        var blogId = 'XXX Your blogId XXX';
        var request = gapi.client.blogger.posts.list({
          'blogId': blogId,
          'maxResults': 100,
        });
        request.execute(renderResults);        
    });
  }
  </script>
  <script src="https://apis.google.com/js/client.js?onload=init"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM