Remote XML


We ve seen that with some effort we can write some wrappers for the various differences between the IE and Mozilla implementations of XML. However, once we get to remote access, we start to see that not only do we face differences in implementation, but differences in security. Specifically, while both browsers are equally happy to load local XML documents using xmlDoc.load() , you will find that remote documents pose a different challenge because of the security considerations each assume. As an example of this, we explore a simple RSS reader implemented in JavaScript.

An RSS Reader in JavaScript

The Really Simple Syndication (RSS) format is used to exchange news items between sites. Many online journals or blogs utilize this format. The RSS format is somewhat standardized ( http://feedvalidator.org/docs/rss2.html ), though there are disagreements and variations. However, roughly an RSS file is defined by an << rss >> root element, which contains a << channel >> that contains an overall << title >>, << link >>, << description >>, and various << item >> tags. Each << item >> in turn can contain a << title >>, << link >>, and << description >>. A very basic RSS file is shown here.

 <<?xml version="1.0" ?>>  <<rss version="2.0">>  <<channel>>   <<title>>RSS Test<</title>>    <<link>>http://www.javascriptref.com<</link>>   <<description>>A fake feed description<</description>>   <<item>>    <<title>>A fake entry<</title>>       <<link>>http://www.javascriptref.com<</link>>    <<description>>Fun fun fun with RSS in this fake entry  description<</description>>   <</item>>   <</channel>> <</rss>> 

Given such a simple format, we could use JavaScript to fetch an RSS file from a Web site and then, using the DOM, filter out the various tags, read their contents, and create (X)HTML elements to display on screen. You might be tempted to use something like

 if(window.ActiveXObject)               var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");       else   if(document.implementation&&document.implementation.createDocument)              xmlDoc=document.implementation.createDocument("","",null);   xmlDoc.async=false; xmlDoc.load(RSSfeedURL); 

and then parse out the RSS appropriately, writing it to the screen. While this will work fine in Internet Explorer, Mozilla will be quite unhappy and won t fetch the content. To explore a cross-platform fix, we instead use a built-in service to fetch XML over HTTP. In Internet Explorer, we need to instantiate the XMLHTTP object:

 request = new ActiveXObject("Msxml2.XMLHTTP"); } 

In Mozilla we can create a similar object:

 request = new XMLHttpRequest(); 

Once the object is created, we can then create and send an HTTP request:

 request.open("GET",feedURL,false);   request.send(null); 

When the response is received we can parse out the various pieces. In this case, we go right for the XML payload itself.

 var feed=request.responseXML; 

Now that we have an object representing the RSS file, we just need to pull out the various tags representing the stories using getElementsByTagName() and then create (X)HTML elements and put them in the page. The complete news reader is shown next with a rendering in Figure 20-11.

click to expand
Figure 20-11: Reading an RSS feed with JavaScript
 <<!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">> <<head>> <<title>>JavaScript RSS Reader<</title>> <<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />> <<style type="text/css">> <<!-- body {font-family:verdana,arial,helvetica,sans-serif; font-size:10pt;} a {color:#003399;} a:hover {color:#FF9900;} #feedOutput {border-style: solid; border-width: 1px; width: 50%; background- color: #FAFAD2; padding: 1em;} -->> <</style>> <<script type="text/javascript">> <<!-- function readRSS(feedURL) {   var request;      /* Create XMLHttpRequest Object */   try {      request = new XMLHttpRequest();   } catch (e) {  request = new ActiveXObject("Msxml2.XMLHTTP"); }   try {   // Needed for Mozilla if local file tries to access an http URL   netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");   } catch (e) {  /* ignore */ }   request.open("GET",feedURL,false);   request.send(null);      var feed=request.responseXML;   var itemList = feed.getElementsByTagName('item');   var numItems=itemList.length;   /* create HTML for the list of items */   var newULTag = document.createElement('ul');      for (var i=0; i<< numItems; i++)     {         /* create a new list item */         var newLITag = document.createElement('li');                /*  get the Title of the item and its' text  */         var itemTitle = itemList[i].getElementsByTagName('title');          var newItemTitleTxt =          document.createTextNode(itemTitle[0].firstChild.nodeValue);                /* build a link to the item */         var itemURL = itemList[i].getElementsByTagName('link');          var newATag = document.createElement('a');          newATag.href = itemURL[0].firstChild.nodeValue;         newATag.appendChild(newItemTitleTxt);                /* get the item's Description */         var itemDescription = itemList[i].getElementsByTagName('description');         var descriptionTxt = document.createTextNode(itemDescription[0].firstChild.nodeValue);         var newPTag = document.createElement('p');         newPTag.appendChild(descriptionTxt);               /* build and append HTML */           newLITag.appendChild(newATag);         newLITag.appendChild(newPTag);          newULTag.appendChild(newLITag);          }   /* output the final HTML of the RSS feed to the page */   document.getElementById('feedOutput').appendChild(newULTag);  } //-->> <</script>> <</head>> <<body>> <<h1 align="center">>Simple JavaScript RSS Reader<</h1>> <<hr />> <<form name="feedForm" id="feedForm"  method="get" action="#">>  <<b>>RSS Feed URL:<</b>> <<input type="text" name="feedURL"  value="http://demos.javascriptref.com/newsfeed.xml" size="50" />>  <<input type="button" value="Display"  onclick="readRSS(this.form.feedURL.value);" />> <</form>> <<div id="feedOutput">>     <<br />> <</div>> <<h2>>For other feeds try<</h2>> <<ul>>   <<li>>http://rss.news.yahoo.com/rss/topstories<</li>>   <<li>>http://www.washingtonpost.com/wp-srv/topnews/rssheadlines.xml<</li>>   <<li>>http://rss.pcworld.com/rss/latestnews.rss<</li>> <</ul>> <</body>> <</html>> 

If you inspect the preceding example closely, you ll notice that the use of the try/catch block to address cross-platform code issues as well as an indication of some potential security issues. Netscape in particular will want you to grant explicit privilege to access a remote site.

click to expand

This makes sense if you consider the implications of remote XML access. As you probe the frontiers of JavaScript, you will find differences between browsers, such as security policies, to be significant. The next few chapters will give you some help here, but as always, you should be very cautious lest you develop code that only works in the browser you happen to use.




JavaScript 2.0
JavaScript: The Complete Reference, Second Edition
ISBN: 0072253576
EAN: 2147483647
Year: 2004
Pages: 209

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net