取得するエントリ数を設定

広告

フィードを取得した場合、明示的に設定していない場合は4つのエントリを取得するように設定されています。ここでは取得するエントリ数を指定する方法について解説します。

1.setNumEntriesメソッド
2.サンプル

フィードを取得する時に取得するエントリ数を指定するにはgoogle.feeds.Feed クラスで用意されている「setNumEntries」メソッドを使います。

setNumEntries(num)

引数には取得したいエントリの数を指定します。

例えば次のように記述します。

var feed = new google.feeds.Feed("http://www.example.com/feed.xml");
feed.setNumEntries(10);
feed.load(function (result){
  if (!result.error){
    /* ... */
  }
});

上記では10個のエントリを取得するように設定しています。

それでは簡単なサンプルで試してみます。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title>Google AJAX Feed API テスト</title>

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="./js/script4_1.js"></script>

</head>
<body>

<p>Google AJAX Feed API テスト</p>
<div id="feed"></div>

</body>
</html>
google.load("feeds", "1");

function initialize() {
  var feedurl = "http://googlejapan.blogspot.com/atom.xml";
  var feed = new google.feeds.Feed(feedurl);
  feed.setNumEntries(3);
  feed.load(function (result){
    if (!result.error){
      var container = document.getElementById("feed");
      var htmlstr = "";
      htmlstr += '<h2><a href="' + result.feed.link + '">' + result.feed.title + '</a></h2>';

      for (var i = 0; i < result.feed.entries.length; i++) {
        var entry = result.feed.entries[i];

        htmlstr += '<h3><a href="' + entry.link + '">' + entry.title + '</a></h3>';
        htmlstr += '<p>' + entry.contentSnippet + '</p>';
        htmlstr += '<p>日付 :' + entry.publishedDate + '</p>';
      }

       container.innerHTML = htmlstr;
    }else{
       alert(result.error.code + ":" + result.error.message);
    }
  });
}

google.setOnLoadCallback(initialize);

上記を実際にブラウザ見てみると次のように表示されます。

p4-1

今回のサンプルでは取得するエントリ数を3つに設定しています。このように任意の数のフィードを取得するように設定することが可能です。

( Written by Tatsuo Ikura )