简体   繁体   English

jQuery:如何使用.load将整个DOM替换为另一个HTML

[英]jQuery: How to replace the whole DOM with another HTML using .load

I have a problem. 我有个问题。 We are doing a Captive Portal. 我们正在做一个强制门户。

Go to any site, for example www.php.net Then in Chrome's console, use this: 转到任何网站,例如www.php.net,然后在Chrome的控制台中使用以下命令:

$("html").load( "https://www.ccc.co.il/Suspend.aspx" );

You will notice, the DOM is replaced, but not quite the way it should be: The wrapper elements of the loaded webpage (title, body for example) are missing! 您会注意到,DOM被替换了,但是不是完全应该这样:所加载网页的包装元素(例如标题,正文)丢失了!

This causes problems of course on the injected page. 这当然会在注入的页面上引起问题。

How do I replace the entire initial DOM? 如何替换整个初始DOM? And please dont suggest to me using a link, or normal redirect. 并且请不要使用链接或正常重定向向我建议。 Those are the restrictions, I need to replace the entire DOM tree please. 这些是限制,我需要替换整个DOM树。

Thanks! 谢谢!

This is fundamentally a feature of browsers. 从根本上讲,这是浏览器的功能。

Here's a snip from the jQuery docs for .load() : 这是jQuery文档中的.load()片段

jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. jQuery使用浏览器的.innerHTML属性解析检索到的文档并将其插入到当前文档中。 During this process, browsers often filter elements from the document such as <html> , <title> , or <head> elements. 在此过程中,浏览器经常从文档中过滤元素,例如<html><title><head>元素。 As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser. 结果,由.load()检索的元素可能与由浏览器直接检索的文档不完全相同。

While I don't recommend what you're suggesting at all, I will attempt to answer your question: 尽管我完全不建议您提出什么建议,但我将尝试回答您的问题:

Using a server-side language (like PHP, for example), return documents as parsed json: 使用服务器端语言(例如PHP),将文档作为已解析的json返回:

{
    "head": [head string],
    "body": [body string]
}

Then your JavaScript can individually replace each element. 然后,您的JavaScript可以单独替换每个元素。 You'll need to switch from .load() to something more configurable, like .ajax() 您需要从.load()切换到更可配置的内容,例如.ajax()

I think you would have to use an iframe in this case as I don't think that you can replace an entire DOM with another. 我认为在这种情况下,您将必须使用iframe,因为我认为您无法将整个DOM替换为另一个。

$('body').html("<iframe height=100% width=100% frameBorder=0 src='https://www.ccc.co.il/Suspend.aspx'></iframe>");

http://jsfiddle.net/c7EbY/ http://jsfiddle.net/c7EbY/

$.get("https://www.ccc.co.il/Suspend.aspx", function(html){$("html").html(html)});

I'm using a regular AJAX function here because it shouldn't strip anything. 我在这里使用常规的AJAX函数,因为它不应剥离任何内容。

Sorry about those 4 html s in a row. 对不起,这4个html连续出现。 :P :P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM