Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

235
Visualizações
Show text file contents inside html body: how to get the result of XMLHttpRequest in a variable I can show on HTML'body?

I have been around this problem for several hours now. My objective is to load the contents of ONE remote text file and display it INSIDE HTML with styles (so "embed" is not a solution as I soon discover). I tried several pieces of code and did more than 100 tests. I manage to solve all problems except one. Even though I can get the content of the file, and even print it in the console, I cannot store this in a variable that I can embed in HTML body code. Below is where I got so far. Thanks for your help.

const url = 'https://12Me21.github.io/test.txt';

function asynchronousCall(callback) {
    const request = new XMLHttpRequest();
    request.open('GET', url);
    request.send();
    request.onload = function() {
        if (request.readyState === request.DONE) {
            console.log('The request is done. Now calling back.');
            callback(request.responseText);
        }
    }
}
asynchronousCall(function(result) {
    console.log('This is the start of the callback function. Result:');
    console.log(result);
    console.log('The callback function finishes on this line. THE END!');
});
console.log('LAST in the code, but executed FIRST!');
<body>
    <h1>the content of the file is:
        <script type="text/javascript">
            document.write(result)
        </script>
    </h1>
</body>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can create an html element with id and then access it by document.getElementById() and set innerText property.

<script>
    const url = 'https://12Me21.github.io/test.txt';

    function asynchronousCall(callback) {
        const request = new XMLHttpRequest();
        request.open('GET', url);
        request.send();
        request.onload = function() {
            if (request.readyState === request.DONE) {
                console.log('The request is done. Now calling back.');
                callback(request.responseText);
            }
        }
    }
    asynchronousCall(function(result) {
        console.log('This is the start of the callback function. Result:');
        console.log(result);
        document.getElementById('content').innerText = result;
        console.log('The callback function finishes on this line. THE END!');
    });
    console.log('LAST in the code, but executed FIRST!');
</script>

<body>
    <h1>the content of the file is:
        <div id="content"></div>
    </h1>
</body>
about 4 years ago · Juan Pablo Isaza Relatório

0

You can simplify the process a bit by using fetch (which is built in to Javascript), and adding the contents of your file into an element on your page:

const url = 'https://12Me21.github.io/test.txt';

let fileContents = document.getElementById('file-contents');

fetch(url)
  .then(response => response.text())
  .then(data => {
    fileContents.innerText = data;
  });
<body>
  <h1>the content of the file is:</h1>
  <span id="file-contents"></span>
</body>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda