Google AJAX Feed APIを使ってブログパーツを作る(その1)

投稿者: | 2008年9月19日

レンタルブログやレンタルホームページといった、PerlやPHP等のプログラムが使えないサイトの中に、外部にある他のサイト(他ドメイン)で公開されているRSSを、Javascriptのみを使って掲載する方法。

通常Javascriptでは別ドメインのファイル(RSS)を取得すること(クロスドメイン処理)は難しいので、Googleが提供しているGoogle AJAX Feed APIを使う。

Google AJAX Feed
http://code.google.com/apis/ajaxfeeds/

■API Keyの取得

Googleのアカウントでログインし、Sign up for the Google AJAX Feed API
http://code.google.com/apis/ajaxfeeds/signup.html
にアクセス。規約を読みチェックを入れたら、掲載するサイトのURLを入れて、「Generate API Key」をクリック。

Thanks for Signing up for a Google AJAX Feed API key!
と共に以下の情報が提供される。

Your key is:あなたのAPI key

This key is good for all URLs in this directory:あなたが入力したURL

サンプルコード
Here is an example web page to get you started:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
  <head>
    <meta http-equiv=”content-type” content=”text/html; charset=utf-8″/>
    <title>Google AJAX Feed API – Simple Example</title>
    <script type=”text/javascript” src=”http://www.google.com/jsapi?key=あなたのKey”></script>
    <script type=”text/javascript”>
    google.load(“feeds”, “1”);
    function initialize() {
      var feed = new google.feeds.Feed(“http://www.digg.com/rss/index.xml”);
      feed.load(function(result) {
        if (!result.error) {
          var container = document.getElementById(“feed”);
          for (var i = 0; i < result.feed.entries.length; i++) {
            var entry = result.feed.entries[i];
            var div = document.createElement(“div”);
            div.appendChild(document.createTextNode(entry.title));
            container.appendChild(div);
          }
        }
      });
    }
    google.setOnLoadCallback(initialize);
    </script>
  </head>
  <body>
    <div id=”feed”></div>
  </body>
</html>