javascript - 想知道为什么我的 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>
解决方案
如果服务器配合,你的代码使用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 只是连接到您的站点。自己的网站。
推荐阅读
- google-chrome-extension - Chrome 扩展程序:是否可以从服务器端启动扩展程序和远程服务器之间的连接?
- c - c函数从txt文件中逐字符读取,将其转换为int并将其存储在链表中
- spring - 如何在 Spring Boot 应用程序的 Redis 缓存管理器中设置不同缓存的最大条目数?
- spring - 如何在 Spring Boot 中捕获 RequestTooBigException
- javascript - 在 vue 模板中渲染一个孩子
- javascript - /dist 中的 index.html 在保存时被删除,并且在 webpack 监视模式期间不会再次重新构建(如果没有更改文件)
- node.js - 当我尝试传递 json 对象进行测试时,Mocha 测试获取“在位置 1 的 JSON 中获取 500 个意外的 JSON o”
- python-3.x - AssertionError: `assert not _is_device_list_single_worker(devices)` 在使用 TF 2.1 的镜像策略在 AI 平台上训练估计器时
- gradle - 当我只删除一个单词时,为什么 Body 构建中的代码会失败?
- python - 无法为具有值 ['type'] 的端点 'topic' 构建 url。你的意思是“topic_func”吗?