来源:www.cncfan.com | 2006-4-27 | (有3333人读过)
前段时间参加了第一届AJAX大赛,结果差了几分,第一轮都没过,郁闷中~~~
其中一题是用AJAX 技术读取RSS种子,感觉对学习AJAX技术很有启发意义,现在把本人的实现代码公布,以供大家学习交流!
题目: 使用XMLHttpRequest读取ajaxcn.org的RSS Feed(http://ajaxcn.org/exec/rss),并用HTML的列表标签(UL/OL/LI)列出获取的的Blog条目.
代码实现:
<!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> <title>RSS Reader</title> <!--copyright Turkeycock--> <script type="text/javascript"> var xmlHttp;
function createXMLHttpRequest() { if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } } function readRSS() { createXMLHttpRequest(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("GET", "http://ajaxcn.org/exec/rss", true); xmlHttp.send(null); } function handleStateChange() { if(xmlHttp.readyState == 4) { if(xmlHttp.status == 200) { clearPreviousResults(); parseResults(); } } }
function clearPreviousResults() { var ListBody = document.getElementById("resultsTitle"); while(ListBody.childNodes.length > 0) { ListBody.removeChild(ListBody.childNodes[0]); } }
function parseResults() { var results = xmlHttp.responseXML; var title = null; var item = null;
var items = results.getElementsByTagName("item"); for(var i = 0; i < items.length; i++) { item = items[i]; title = item.getElementsByTagName("title")[0].firstChild.nodeValue;
addListRow(title); }
}
function addListRow(title) { var row = document.createElement("ul"); var cell = createCellWithText(title); row.appendChild(cell); document.getElementById("resultsTitle").appendChild(row); }
function createCellWithText(text) { var cell = document.createElement("li"); var textNode = document.createTextNode(text); cell.appendChild(textNode); return cell; } </script> </head>
<body> <h2>Blog文章列表</h2> <form action="#"> <input type="button" value="搜索" onclick="readRSS();"/> </form> <div id="resultsTitle"></div> </body> </html>
部署到web容器中就可以运行,我是在Tomcat 5.5中运行的,可以正确读取RSS种子!
|