14 April 2009

Reading an rss feed using JavaScript

Wrote this last night for my brother. It's a simple JavaScript class that reads from an rss file on the server and loads the entries into an HTML element. He has a blog (Wordpress) and a separate, static page that he wanted to be dynamically updated with recent posts. JavaScript and Ajax (plus some ghetto-parsing) was the quickest way I could think to get it done. Could XSLT be integrated somehow? I'm not sure.

The JavaScript file is called feed-injector.js and it requires Prototype 1.6+. Thanks to Alex Vollmer's article on object-oriented Ajax (along with his many commenters) to clean up the callback code.

There's very little magic here. Basically, the code makes an Ajax call to the requested rss file, parses out N entries containing title, link, and description elements, and then generates divs in the specified parent div. Example use (also using Prototype for the window load event):

  1. // For http://example.com/mysite/mysite.rss
  2. Event.observe(window, "load", function() {
  3.     var fi = new FeedInjector("/mysite/mysite.rss");
  4.     fi.load();
  5. });

Ajax can't call across domains so no funny business, mister. This is usually resolved by a "proxy" on your server that makes the remote call (i.e. my.domain.com/ajax.html -> my.domain.com/proxy.php -> other.domain.com and back). YMMV.

[ updated 29 Apr 2009 ]

Or, you could just create a FeedBurner account. These articles are ad-heavy, but they or their comments may add information: Display and Show Feed on HTML Website with FeedBurner BuzzBoost, Google Lets You Embed Feeds on Your Site. Another article, How to Embed RSS Feeds into HTML Web Pages - The Easy Way, shows how to add feeds to your Google home page and has many comments with other possible solutions.

[ posted by sstrader on 14 April 2009 at 3:23:59 PM in Programming ]