我想知道为什么我的XML URL提要数据不能在前端显示为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>发布于 2021-07-29 06:11:44
如果服务器进行合作,您使用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只是连接到您自己的站点。
https://stackoverflow.com/questions/68504494
复制相似问题