2008年1月15日

Google AJAX Feed API

Google.com serves as a proxy to the outside feeds。

Google AJAX Feed APIGoogle AJAX API的一個分支,簡單來說就是連到Google來取得feed,本質上仍是使用script tag的方式突破same-origin policy取得資料。

  • 說明上說要先申請一個Google API key,雖然要輸入使用的URL(說明上說在此URL下所有的子目錄都可以使用,且可以用不同的URL申請),但是我用部落格申請的key,在個人電腦上也可以用,好像並沒有限制,甚至沒有key也可以用。
  • 依照Developer's Guide的說明,使用起來非常直覺簡單。
  • 有提供JSON、XML、Conbined JSON/XML三種資料格式,JSON格式將RSS或Atom的部分常用元素轉成對應的欄位,並統一名稱,並沒有全部轉換,XML格式可以使用google.feeds.getElementsByTagNameNS來取得擴充的資料。
  • feed資料由crawler(Feedfetcher)取得,所以不一定是最新的。
  • 可以設定取得資料的數量,預設是4個。
  • 對於一般的資料顯示,有FeedControl可以直接用,另外還有提供一些成品可以套用(請參考ExampleBlog)。
  • 甚至可以做feed的查詢及探知

範例

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");

function initialize() {
  var feed = new google.feeds.Feed("http://api.flickr.com/services/feeds/photos_public.gne?tags=羅平,油菜花,sunset&tagmode=all");
  feed.setResultFormat(google.feeds.Feed.MIXED_FORMAT);
  feed.load(function(result) {
    if (!result.error) {
      var div = document.getElementById("flickr photos");
      for (var i = 0; i < result.feed.entries.length; i++) {
        var entry = result.feed.entries[i];
        var img = document.createElement("img");
        var imgLink = google.feeds.getElementsByTagNameNS(entry.xmlNode, "http://www.w3.org/2005/Atom", "link")[2];
        img.setAttribute("src", imgLink.getAttribute("href"));
        img.setAttribute("title", entry.title);
        img.setAttribute("width", "200");
        img.setAttribute("height", "116");
        var a = document.createElement("a");
        a.setAttribute("href", entry.link);
        a.setAttribute("target","_blank");
        a.appendChild(img);
        div.appendChild(a);
      }
    }
  });
}

google.setOnLoadCallback(initialize);
</script>

動態載入updated on 2008-04-18

基本上使用Google AJAX API loader載入所需的模組分為兩個階段:

  1. <script type="text/javascript" src="http://www.google.com/jsapi"></script> 建立google、google.loader模組及相關函式
  2. 使用google.load(moduleName, moduleVersion, optionalSettings)載入所需要的AJAX API模組,例如google.load("feeds","1")載入google.feeds模組

Google對這兩個階段都提供了動態載入的支援 (參考:blogdoc):

  1. 加上callback參數,動態插入<script type="text/javascript" src="http://www.google.com/jsapi&callback=YOUR_CALLBACK"></script>,載入完成後會執行所指定的回呼函式。
  2. 傳入callback參數,google.load(..., ..., {"callback": YOUR_CALLBACK})會使用動態插入script tag的方式載入模組,完成後會執行所指定的回呼函式。

0 comments:

張貼留言