首页 > 解决方案 > 想知道为什么我的 XML URL Feed 数据没有在前端显示为 HTML。如果我在我的目录中托管静态 XML,它可以工作

问题描述

想知道为什么我的 XML URL Feed 数据没有在前端显示为 HTML。如果我在我的目录中托管静态 XML,它就可以工作。但是,当使用来自https://www.prlog.org/news/us/ind/sports/rss.xml的实时提要时,它不起作用???

<!doctype html>
<html lang="en">
  <head>
    <title>Test XML Feed</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  </head>
  <body>
        <div class="jumbotron jumbotron-fluid">
            <div class="container">
                <h1 class="display-8">Testing XML Feed</h1>
                <hr class="my-2">
                <div class="row">
                    <div class="col-12">
                        <div id="title"></div>
                    </div>
                    <div class="col-12">
                        <div id="description"></div>
                    </div>
                </div>
             </div>
         </div>
      
      <script>
        //Display it
        function displayFEED(i) {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    myFunction(this, i);
                }
            };
            //Call XML Feed with Live URL
            xmlhttp.open("GET", 'https://www.prlog.org/news/us/ind/sports/rss.xml', true);
            xmlhttp.send();
        }
        displayFEED(1);


        // Call tag names from XML and match ID's
        function myFunction(xml, i) {
            var xmlDoc = xml.responseXML; 
            x = xmlDoc.getElementsByTagName("channel");
            document.getElementById("title").innerHTML = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
            document.getElementById("description").innerHTML = x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
         
        }
        </script>
  </body>
</html>

标签: javascripthtmlxmltwitter-bootstraprss

解决方案


如果服务器配合,你的代码使用XMLHttpRequest可以拉取远程资源;对于下面的示例子域,我已经配置了标头,这样在 stackoverflow.com 上运行的代码可以正常访问文件:

const uri = 'https://cors-resources.liberty-development.net/sample1.xml';

const req = new XMLHttpRequest();
req.open('GET', uri);
req.onload = function(e) {
  console.log(req.responseXML);
};
req.send();

但是,如果服务器不合作,您只能在您自己的站点上设置某种代理服务,并让它在您自己的站点上使用服务器端代码拉取远程 URI,而客户端 JavaScript 只是连接到您的站点。自己的网站。


推荐阅读