【问题标题】:Get HTML content of remote page with JS用JS获取远程页面的HTML内容
【发布时间】:2020-03-27 03:53:01
【问题描述】:

如何从远程网站拉取 HTML 内容——远程 PHP 脚本的输出——在不运行 Web 服务器和 使用纯 JS 的情况下由 .html 文件显示/strong>(如果 vanillaJS 太复杂,则为 Ajax)。

不能将 https://quarantine.country/coronavirus/cases/usa/ 输出包含到 covid 应用程序(没有 apache,仅 html)和 jQuery 太大(!)?

我们需要这个输出:

<html><head></head><body>In the US we have 79082 reported cases with 76075 still active. 1864 recovered and 1143 casualties. The death ratio in the US is 0.01 at the moment, 0.02 is recovering. Last update at 2020/03/26.
In the same time, we have 520755 total cases worldwide, with 23581 deaths and 122690 recovered, a 0.05/0.24 ratio.
</body></html>

*使用 JS 加载并包含远程脚本 (index.php) 的 html 输出应该可以解决问题。一个简单的解决方案会有很大帮助。谢谢!

【问题讨论】:

  • 两者都可以,按原样获取纯文本或完整的 HTML 输出。谢谢!

标签: javascript html post get cross-domain


【解决方案1】:

首先,您的网络服务器需要返回 HTTP 标头

Access-Control-Allow-Origin,您可以在此处了解更多信息:CORSAccess-Control-Allow-Origin: * 允许所有网站访问您的网络服务器。然后,您可以使用 XMLHttpRequest:

function onReceive() {
  console.log(this.responseText);
}

const req = new XMLHttpRequest();
req.addEventListener("load", onReceive);
req.open("GET", "https://quarantine.country/coronavirus/cases/usa/");
req.send();

编辑:如果您不控制quarantine.country 网站,那么如果没有他们的协作或您自己的网络服务器,这是不可能的。

【讨论】:

  • 非常感谢,尤其是“CORS 编辑:”错过了相关部分,完全有意义
猜你喜欢
  • 1970-01-01
  • 2012-07-28
  • 2012-06-04
  • 2010-11-21
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多