Javascript Ajax异步读取RSS文档具体实现

前端技术 2023/09/01 JavaScript

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);
        }
    }
}

本文地址:https://www.stayed.cn/item/2109

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。