Come si carica una pagina HTML in un <div> usando JavaScript?

Voglio che home.html sia caricato in <div id="content">.

<div id="topBar"> <a href ="#" onclick="load_home()"> HOME </a> </div>
<div id ="content"> </div>
<script>
      function load_home(){
            document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
  }
</script>

Questo funziona bene quando uso Firefox. Quando uso Google Chrome, mi chiede il plug-in. Come faccio a farlo funzionare in Google Chrome?

Soluzione

Finalmente ho trovato la risposta al mio problema. La soluzione è

function load_home() {
     document.getElementById("content").innerHTML='';
}
Commentari (8)

Potete usare la funzione jQuery load:

<div id="topBar">
    <a href ="#" id="load_home"> HOME </a>
</div>
<div id ="content">        
</div>

<script>
$(document).ready( function() {
    $("#load_home").on("click", function() {
        $("#content").load("content.html");
    });
});
</script>

Scusa. Modificato per l'on click invece che on load.

Commentari (1)

Fetch API

function load_home (e) {
    (e || window.event).preventDefault();

    fetch("http://www.yoursite.com/home.html" /*, options */)
    .then((response) => response.text())
    .then((html) => {
        document.getElementById("content").innerHTML = html;
    })
    .catch((error) => {
        console.warn(error);
    });
} 

XHR API

function load_home (e) {
  (e || window.event).preventDefault();
  var con = document.getElementById('content')
  ,   xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function (e) { 
    if (xhr.readyState == 4 && xhr.status == 200) {
      con.innerHTML = xhr.responseText;
    }
  }

  xhr.open("GET", "http://www.yoursite.com/home.html", true);
  xhr.setRequestHeader('Content-type', 'text/html');
  xhr.send();
}

in base ai tuoi vincoli dovresti usare ajax e assicurarti che il tuo javascript sia caricato prima del markup che chiama la funzione load_home().

Riferimento - davidwalsh

MDN - Usare Fetch

[JSFIDDLE demo](http://jsfiddle.net/jpmCz/)

Commentari (4)