【问题标题】:How to reference HTML from external webpage如何从外部网页引用 HTML
【发布时间】:2015-02-11 18:35:12
【问题描述】:

我提前为这个基本问题道歉。

我的网页 A 上有指向网页 B 的链接。我需要找到指向网页 B 的链接(很简单),然后将网页 B 中的 HTML 存储在我的 javascript 脚本中的一个变量中。

要存储来自网页 A 的 HTML,我知道这很简单:

html_A = document.body.innerHTML;

如何存储来自网页 B 的 HTML?我相信我需要正确使用 AJAX?或者我可以用javascript来做吗?如果是前者,我们就假设网页 B 的服务器允许这样做。

提前谢谢你!

【问题讨论】:

标签: javascript jquery html ajax


【解决方案1】:

如果您尝试从位于不同服务器上的网站加载 HTML,您将收到 Cross-Origin Request Blocked 错误。我过去处理过这个问题,并找到了一种使用 YQL 的方法。试试看:

//This code is located on Website A
$(document).ready(function() {
    var websiteB_url = 'http://www.somewebsite.com/page.html';
    var yql = '//query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + websiteB_url + '"') + '&format=xml&callback=?';
    $.getJSON(yql, function(data) {
        function filterDataCUSTOM(data) {
            data = data.replace(/<?\/body[^>]*>/g, '');// no body tags
            data = data.replace(/[\r|\n]+/g, ''); // no linebreaks
            return data;
        }
        if (data.results[0]) {
            var res = filterDataCUSTOM(data.results[0]);
            $("div#results").html(res);
        } else {
            console.log("Error: Could not load the page.");
        }
    });
});

【讨论】:

  • 哎呀!雅虎公开了该功能?知道他们为缓存做了什么吗?另外,我不确定我是否理解您的查询。您在 url 中将格式指定为 xml,但 getJSON 将格式设置为 Json(这是您返回的)。您还附加了用于 jsonp 的 &amp;callback=?,但您显然没有使用 jsonp。
【解决方案2】:

这只有在网页 B 由于 the same-origin policy security feature of all major browsers 而位于同一域中时才有可能。

如果两个页面在同一个域上,你可以这样做

$.get("/uri/to/webpage/b").then(function(html) {
     //do something with the html;
});

请注意,只有在 .then(...) 函数内完成 ajax 请求后,该 html 才可用。它将在此代码块之后的行上可用。

如果不进一步了解您的情况,很难说,但这很少是正确的做法。您可能想查看 $.fn.load()(受 SOP 限制)或使用 iframes(不受 SOP 限制),因为其中一种可能更合适。

我应该注意,当您需要从另一个域访问 html 时,执行此操作的标准方法是将其拉到您的网络服务器上,然后从那里重新提供它。话虽如此,这可能违反了该网站的使用条款。

【讨论】:

  • 我同意。如果您尝试从其他域获取页面,您将收到如下错误:Cross-Origin request blocked: The Same Origin Policy disallows reading the remote resource at WEBSITE B. this can be fixed by moving the resource to the same domain or enabling CORS
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
相关资源
最近更新 更多