使用 JavaScript 获取另一个域中另一个页面的 HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5615869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:46:13  来源:igfitidea点击:

Get HTML of another page in another domain using JavaScript

javascriptjavascript-framework

提问by Vin

Right now, I am using curl in PHP to get the HTML source code of some remote web page.

现在,我在 PHP 中使用 curl 来获取某个远程网页的 HTML 源代码。

Is there any way I can get the same HTML source code of some cross-domain web page in JavaScript? Any tutorials?

有什么方法可以在 JavaScript 中获得某些跨域网页的相同 HTML 源代码?有教程吗?

回答by Amr Elgarhy

I think you need to know about JSONPto access cross-domain web pages in js

我想你需要了解JSONP才能在js中访问跨域网页

https://stackoverflow.com/questions/tagged/jsonp?sort=votes

https://stackoverflow.com/questions/tagged/jsonp?sort=votes

回答by Bosh

Q. How is this any different than issuing an AJAX "GET http://otherdomain.com/page.html" call?

问:这与发出 AJAX“GET http://otherdomain.com/page.html”调用有何不同?

A. The same-origin policy checks the HTTP response headers for AJAX requests to remote domains, and if they don't contain a suitable Access-Control-Allow-Originheader, the request fails.

A. 同源策略会检查 AJAX 请求到远程域的 HTTP 响应标头,如果它们不包含合适的Access-Control-Allow-Origin标头,请求将失败。

So, there are two ways to make this work:

因此,有两种方法可以使这项工作:

  • If you control the other domain, you can include the following header in the HTTP response:

    Access-Control-Allow-Origin: *
    (details at MDC)

  • If you don't, you're stuck implementing a server-side proxy (for example, this simple PHP proxy).

  • 如果您控制其他域,则可以在 HTTP 响应中包含以下标头:

    Access-Control-Allow-Origin: *
    (详情请见MDC

  • 如果您不这样做,您将无法实现服务器端代理(例如,这个简单的 PHP 代理)。

In any case, once you implement one of the two options above, you're left with a simple AJAX call:

在任何情况下,一旦您实现了上述两个选项之一,您就会得到一个简单的 AJAX 调用:

$.ajax({
  url: "http://mydomain.com/path/to/proxy.php?url="+
        encodeURI("http://otherdomain.com/page.html"),
  dataType: "text",
  success: function(result) {
    $("#result").text(result);
  }
});

回答by David

This solution I just found might be of use like the other workarounds...

我刚刚发现的这个解决方案可能像其他解决方法一样有用......

http://www.ajax-cross-domain.com/

http://www.ajax-cross-domain.com/