RSS 是一種基於XML的檔案標準,透過符合RSS 規範的XML檔案可以簡單實現網站之間的內容共享。 Ajax 是Asynchronous JavaScript and XML的縮寫。透過Ajax 技術可以經由超文本傳輸協定(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);
}
}
}