Show content in my body, with JS

0

What I would like to do, is that in my index.html, in the part of the body the entire page is loaded, let's say it hits "contacts" of the nav, and it loads me the contents of a contacts.html file, inside the body.

<html>

<head>
    <title>Hola Mundo</title>
    <script src="js\main.js"></script>
</head>
<body>
    <header>
        <h1>Hola Mundo</h1>
    </header>
    <nav>
        <button id="Inicio" name="Inicio">Inico</button>
        <button id="Contactos" name="Contactos">Contactos</button>
    </nav>

    <body id="Cuerpo">
        <!-- aqui quiero que me cargue todo al presionar algún button del divsi presiono en el button contacto, me cargue contactos.html, si le doy a inicio me cargue inicio.html, y muestre el contenido dentro del body -->
    </body>
</body>

</html>
    
asked by Furiduri 18.09.2018 в 21:23
source

1 answer

0

Inside a folder on your computer create a text file contenido.txt and other index.html

In the index.html put this:

<div id="Cuerpo">
    <!-- aqui quiero que me carge todo al precionar algun botton del div -->
</div>

<script>

function leerFichero(fichero)
{
    var miContenido = new XMLHttpRequest();
    miContenido.open("GET", fichero, false);
    miContenido.onreadystatechange = function ()
    {
        if(miContenido.readyState === 4)
        {
            if(miContenido.status === 200 || miContenido.status == 0)
            {
                var miTexto = miContenido.responseText;
                Cuerpo.innerHTML = miTexto;
            }
        }
    }
    miContenido.send(null);
}

leerFichero('contenido.txt');

</script>

In contenido.txt put this:

<h1>TEST</h1><p>Alguna cosa m&aacute;s</p>

When opening the index.html you should see the header and the paragraph. Of course, you can call the leerFichero function by clicking on a button.

I hope this is useful

    
answered by 18.09.2018 в 21:50