如何从外部网页的HTML引用 [英] How to reference HTML from external webpage

查看:172
本文介绍了如何从外部网页的HTML引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提前为基本的问题深表歉意。

I apologize in advance for the rudimentary question.

我有网页A,有一个链接就可以了网页B。我需要找到的链接到网页B(很容易),然后存储从网页B的HTML中的变量在我的javascript脚本。

I have web page A that has a link to web page B on it. I need to locate the link to web page B (easy enough), and then store the HTML from web page B in a variable in my javascript script.

要存储从网页A上的HTML,我知道这是一个简单的:

To store the HTML from web page A, I know it's a simple:

html_A = document.body.innerHTML;

我如何存储从网页B的HTML?我相信,我需要使用AJAX正确吗?或者,我可以做到这一点的JavaScript?如果是前者,我们只是假设服务器网页B允许的。

How do I store the HTML from web page B? I believe I need to use AJAX correct? Or can I do it with javascript? And if it's the former, let's just assume the server for web page B allows for it.

感谢你在前进!

推荐答案

如果您选择尝试从驻留,你会得到一个跨域请求阻止在不同的服务器上的网站加载HTML 错误。我过去处理了这一点,并找到一种方法,使用YQL做到这一点。试试吧:

If youre trying to load HTML from a website that resides on a different server you will get a Cross-Origin Request Blocked Error. I dealt with this in the past and found a way to do it using YQL. Try it out:

//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.");
        }
    });
});

这篇关于如何从外部网页的HTML引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆