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):
// For http://example.com/mysite/mysite.rss
Event.observe(window, "load", function() {
var fi = new FeedInjector("/mysite/mysite.rss");
fi.load();
});
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.
- Techniques after using Swift for a month posted by sstrader on 26 August 2015 at 11:41:51 PM
- Some thoughts on Ruby after finishing a week (minus one day) of training posted by sstrader on 15 December 2011 at 8:59:30 PM
- Links on the singleton pattern posted by sstrader on 9 December 2011 at 9:19:50 AM
- Phonebot posted by sstrader on 29 October 2011 at 6:37:05 PM
- The labeled break in Java posted by sstrader on 4 September 2011 at 11:27:56 AM