Html 如何在没有 IFRAME 和 JQuery 的情况下使用 Javascript 在 div 中加载网页?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15211969/
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-08-29 06:08:21  来源:igfitidea点击:

How do I load a webpage inside a div using Javascript without IFRAME and JQuery?

javascripthtmlcss

提问by Jay

I need to load an external webpage into a div. I don't want to use an iFrame. And I want this done with plain Javascript. I'm not sure how to go about it.

我需要将外部网页加载到 div 中。我不想使用 iFrame。我想用普通的 Javascript 来完成。我不知道该怎么做。

回答by Quentin

With difficulty…

有困难…

Use Ajax (e.g. via XMLHttpRequest) to get the page. Since it is external, you will need to bypass the same origin policy.

使用 Ajax(例如通过XMLHttpRequest)来获取页面。由于它是外部的,您将需要绕过同源策略

Once you have the page, extract the relevant parts of it (probably the children of the bodyelement) and add that to your existing DOM.

获得页面后,提取其中的相关部分(可能是body元素的子元素)并将其添加到现有的 DOM 中

You'll need to account for differing stylesheets between your site and the external one, for relative URIs (to resources on the external site that aren't on yours), and for any scriptsin the remote content.

您需要考虑站点和外部站点之间的不同样式表、相对 URI(外部站点上不属于您的资源)以及远程内容中的任何脚本

回答by Patrick Mutwiri

Whichever method you have, in js, try this instead : $('#myid').load('mylink.com')

无论你有哪种方法,在 js 中,试试这个: $('#myid').load('mylink.com')

I know only this in js.

我在js中只知道这个。

回答by theaccordance

You should be able to load html pages within a page using the jQuery.get() method. I'm using this method for two websites for my clients, where the individual pages are different sections of the site.

您应该能够使用 jQuery.get() 方法在页面内加载 html 页面。我正在为我的客户在两个网站上使用这种方法,其中各个页面是网站的不同部分。

I'm unsure of the behavior you may encounter if you attempt to use this method loading full HTML pages that include header information and the body tag. I recommend using it to load HTML snippets.

如果您尝试使用此方法加载包含标题信息和正文标记的完整 HTML 页面,我不确定您可能会遇到的行为。我建议使用它来加载 HTML 片段。

jQuery.get()

jQuery.get()

回答by kennebec

You don't even need javascript-

你甚至不需要 javascript-

but the same restrictions apply as for iframe inclusion of different domains.

但同样的限制适用于不同域的 iframe 包含。

<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>test page</title>
</head>
<body>

<div> 
<object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
</object></div>
</div>


</body>
</html>