admin管理员组

文章数量:1134247

I'm quite sure this a common question, but I'm pretty new to JS and am having some trouble with this.

I would like to load x.html into a div with id "y" without using iframes. I've tried a few things, searched around, but I can't find a decent solution to my issue.

I would prefer something in JavaScript if possible.

I'm quite sure this a common question, but I'm pretty new to JS and am having some trouble with this.

I would like to load x.html into a div with id "y" without using iframes. I've tried a few things, searched around, but I can't find a decent solution to my issue.

I would prefer something in JavaScript if possible.

Share Improve this question edited Dec 21, 2022 at 22:51 starball 49.3k28 gold badges194 silver badges865 bronze badges asked Aug 20, 2010 at 21:35 MapWebMapWeb 7751 gold badge6 silver badges6 bronze badges 2
  • If that's the only way of doing it, I guess it would be okay. I've never used jQuery though.. – MapWeb Commented Aug 20, 2010 at 21:41
  • 1 Its not the only way, but it does abstracts away most of the complexity a problem like this brings. Also, remember that because of security concerns you cannot load HTML from other sites (different domain names) with Javascript – Yi Jiang Commented Aug 20, 2010 at 21:46
Add a comment  | 

8 Answers 8

Reset to default 117

Wow, from all the framework-promotional answers you'd think this was something JavaScript made incredibly difficult. It isn't really.

var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
    if (this.readyState!==4) return;
    if (this.status!==200) return; // or whatever error handling you want
    document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();

If you need IE<8 compatibility, do this first to bring those browsers up to speed:

if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
    window.XMLHttpRequest= function() {
        return new ActiveXObject('MSXML2.XMLHttp');
    };
}

Note that loading content into the page with scripts will make that content invisible to clients without JavaScript available, such as search engines. Use with care, and consider server-side includes if all you want is to put data in a common shared file.

jQuery .load() method:

$("#y").load("x.html");

Using fetch

<script>
fetch('page.html')
  .then(response=> response.text())
  .then(text=> document.getElementById('elementID').innerHTML = text);
</script>

<div id='elementID'> </div>

fetch needs to receive a http or https link, this means that it won't work locally.

Note: As Altimus Prime said, it is a feature for modern browsers

2021

Two possible changes to thiagola92's answer.

  1. async await - if preferred

  2. insertAdjacentHTML over innerText (faster)

    <script>
    async function loadHtml() {
         const response = await fetch("page.html")
         const text = await response.text()
         document.getElementById('elementID').insertAdjacentText('beforeend', text)
    }
    
    loadHtml()
    </script>
    <!-- ... -->
    <div id='elementID'> </div>
    

I'd suggest getting into one of the JS libraries out there. They ensure compatibility so you can get up and running really fast. jQuery and DOJO are both really great. To do what you're trying to do in jQuery, for example, it would go something like this:

<script type="text/javascript" language="JavaScript">
$.ajax({
    url: "x.html", 
    context: document.body,
    success: function(response) {
        $("#yourDiv").html(response);
    }
});
</script>
    document.getElementById("id").innerHTML='<object type="text/html" data="x.html"></object>';

There was a way to achieve this in the past, but it was removed from the specification, and subsequently, from browsers as well (e.g. Chrome removed it in Chrome 70). It was called HTML imports and it originally was part of the web components specs.

Currently folks are working on a replacement for this obviously lacking platform feature, which will be called HTML modules. Here's the explainer, and here's the Chrome platform status for this feature. There is no milestone specified yet as of when this feature will land.

Chances are the syntax is going to look similar to this:

import { content } from "file.html";

Resolving the remaining issues with HTML modules I assume might take quite some time, so until then the only viable options you have is to have

  • either your build stack resolve the issue for you (e.g. with webpack-raw-loader (Webpack 4), or with asset modules (Webpack 5)),
  • or to rely on async fetch to get the job done (which might result in a less-than-optimal performance experience).

We already have JSON modules and CSS module scripts (which both were sorely missing features for a long time as well).

http://www.boutell.com/newfaq/creating/include.html

this would explain how to write your own clientsideinlcude but jQuery is a lot, A LOT easier option ... plus you will gain a lot more by using jQuery anyways

本文标签: javascriptLoad HTML File Contents to Div without the use of iframesStack Overflow