Ajay Malik
Ajay Malik

Reputation: 329

How to retrieve all posts using blogger API by using JavaScript loop

I am trying To Get List of all Blog Posts Using Blogger API by using javascript Loop. I found a solution in StackOverflow too. but that didn't work for me.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
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/5039479718685240371/posts?callback=handleResponse&key=AIzaSyDxfWmXTRnO5yIp25NvuUEBWKSa_5mqjHA"></script>

below error was occur when I run This Code:{ "message": "Uncaught ReferenceError: $ is not defined", "filename": "https://stacksnippets.net/js", "lineno": 17, "colno": 5 }

Upvotes: 1

Views: 2982

Answers (1)

Andrew L
Andrew L

Reputation: 5486

I did some trial and error with your code and the first problem you noted was solved by including the jQuery library.

You can use ajax to GET the data instead of including it in a script tag. jQuery will register and call the callback function for you.

The rest worked. Here is a example. I would also suggest changing your key now.

$.ajax("https://www.googleapis.com/blogger/v3/blogs/5039479718685240371/posts?callback=handleResponse&key=AIzaSyDxfWmXTRnO5yIp25NvuUEBWKSa_5mqjHA")

function handleResponse(response) {
  //var post_number = Object.keys(response.items).length; //number of posts
  for (i = 0; i < response.items.length; i++) {
    var titleHtml = '<div id="post' + (i + 1) + '" class="post"><p>' + response.items[i].title + '</p></div>';
    $('#content').append(titleHtml);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>

Upvotes: 2

Related Questions