首页 > 解决方案 > 在不被阻止的情况下获取 XML (CORB)

问题描述

例如,我想获取https://www.w3schools.com/xml/simple.xml 到我的网站http://example.com

这是代码

var xhr = new XMLHttpRequest();
xhr.open("GET", 'https://www.w3schools.com/xml/simple.xml', true);
xhr.onload = function () {
  if (xhr.readyState === 4 && this.status === 200) {
    console.log(this);
 }
}

xhr.send();

我得到一个空洞的回应和一个警告说

Cross-Origin Read Blocking (CORB) blocked cross-origin response https://www.w3schools.com/xml/simple.xml with MIME type text/xml. See https://www.chromestatus.com/feature/5629709824032768 for more details.

然后我一直在研究这些CORB规则。一些开发人员说不可能从其他来源获取数据。但真的是这样吗?

在我正在处理的项目中,它是一个公共 xml 提要,并且由于所有者经常更新提要 - 我希望我的网站与提要同步 - 我认为这是不可能的?我真的必须创建一个 xml 文件,然后每次都复制粘贴 xml 数据并将其上传到我的服务器吗?

或者有没有办法以某种方式直接从 url 获取这些数据?

标签: javascriptxml

解决方案


你可以像这样创建一个 PHP 脚本:

<?php
    header("Content-type: text/xml");
    echo file_get_contents('https://www.w3schools.com/xml/simple.xml');
?>

调用它simple.php,然后修改你的 Javascript 来调用simple.php

var xhr = new XMLHttpRequest();
xhr.open("GET", 'simple.php', true);
xhr.onload = function () {
  if (xhr.readyState === 4 && this.status === 200) {
    console.log(this);
 }
}

xhr.send();

推荐阅读