RSS 是一種基於 XML的檔案標準,通過符合 RSS 規範的 XML檔案可以簡單實現網站之間的內容共用。Ajax 是Asynchronous JavaScript and XML的縮寫。通過 Ajax 技術可以經由超文字傳輸通訊協定 (HTTP)(Http) 向一個伺服器發出請求並且在等待該響應時繼續處理另外的資料。通過 Ajax 技術可以很容易實現讀取遠程 XML檔案,因此,可以使用 Ajax技術實現遠端存取依據 RSS 標準產生的摘要資訊,甚至我們可以自己寫一個 RSS 讀取程式。
Ajax 並不是一門新的語言或技術, 它實際上是幾項技術按一定的方式組合在一起。共同在協作中發揮各自的作用, 它包括:使用XHTML 和CSS 標準化呈現; 使用DOM 實現動態顯示和互動; 使用XML 和XSLT 進行資料交換與處理; 使用XMLHttpRequest進行非同步資料讀取; 最後用 JavaScript 綁定和處理所有資料。好了,對於理論就不在多說了,下面我們直接看代碼吧。
建立XMLHttpRequest對象並將請求發送到伺服器:
複製代碼 代碼如下:
function createXHR(url){
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open("post",url,"false");
xmlHttp.onreadystatechange = getResponse; xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(null);
}
通過DOM操作對Rss文檔進行遍曆,得到需要的值:
複製代碼 代碼如下:
function readDoc(doc){
root = doc.getElementsByTagName("channel")[0];
docTitle = root.getElementsByTagName("title")[0];
docLink = root.getElementsByTagName("link")[0];
docDescription = root.getElementsByTagName("description")[0];
items = root.getElementsByTagName("item");
for(var i=0;i<items.length;i++){
itemTitle = items[i].getElementsByTagName("title")[0];
itemLink = items[i].getElementsByTagName("link")[0];
itemDescription = items[i].getElementsByTagName("description")[0];
//itemPubDate = items[i].getElementsByTagName("pubDate")[0];
document.getElementById("rssTitle").innerHTML = docTitle.firstChild.nodeValue;
temp = "</h1><h2><a href=""+itemLink.firstChild.nodeValue+"" target="_blank">"+itemTitle.firstChild.nodeValue+"</a></h2>"+"<p>"+itemDescription.firstChild.nodeValue+"</p><hr/>";
document.getElementById("readRss").style.display = "none";
document.getElementById("printRss").getElementsByTagName("span")[0].style.display = "none";
document.getElementById("printRss").innerHTML = document.getElementById("printRss").innerHTML + temp;
}
}
調用createXHR(url)函數,傳入參數,向伺服器發送求:
複製代碼 代碼如下:
createXHR("http://www.apple.com.cn/hotnews/rss/hotnews.rss");
得到響應:
複製代碼 代碼如下:
function getResponse(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
rssDoc = xmlHttp.responseXML;
readDoc(rssDoc);//調用readDoc()函數
}else{
document.getElementById("rssTitle").innerHTML = "讀取異常!";
//alert(xmlHttp.status);
}
}
}