Insert an HTML code in a client-side way without using PHP [duplicate]

0

Personal I have two external files called header.html and footer html containing headers and footers of a website, with menus and etc. I need to include these external files in the pages of the site without the use of PHP.

There's something like:

<?php require_once("include/header.html"); ?>

Making use of javascript or otherwise that is Client-side and not Server-side as in other answers?

    
asked by anonymous 11.10.2017 / 00:06

2 answers

1

Create a div in each location you want to load the files with id s header and footer and pull them via Ajax:

var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
    http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
    http = new XMLHttpRequest();
}

var paginas = ["header","footer"];

window.onload = function(){
    carrega_paginas(0);
}

function carrega_paginas(i){
    http.open("GET",paginas[i]+".html",true);
    http.onreadystatechange=function(){
        if(http.readyState==4){
            document.getElementById(paginas[i]).innerHTML = http.responseText;
            if(i == 0){
                carrega_paginas(1);
            }
        }
    }
    http.send(null);
}
    
11.10.2017 / 04:31
0

In javascript:

const ajax = (url, cb, data) => {
    const xhr = new XMLHttpRequest();
    xhr.addEventListener("readystatechange", () => {
        if (this.readyState == 4 && this.status == 200) cb(this.responseText);
    })
    xhr.open(data?"get":"post", url, true);
    xhr.setRequestHeader("Content-type:", "application/x-www-form-urlencoded");
    xhr.send(data);
}
ajax("header.php", conteudo => document.body.appendChild(conteudo));
    
11.10.2017 / 00:20