前段時間參加了第一屆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種子!