He estado alrededor de este problema durante varias horas. Mi objetivo es cargar el contenido de UN archivo de texto remoto y mostrarlo DENTRO de HTML con estilos (así que "incrustar" no es una solución como pronto descubro). Probé varias piezas de código e hice más de 100 pruebas. Logro resolver todos los problemas excepto uno. Aunque puedo obtener el contenido del archivo e incluso imprimirlo en la consola, no puedo almacenarlo en una variable que pueda incrustar en el código del cuerpo HTML. A continuación se muestra dónde llegué hasta ahora. Gracias por tu ayuda.
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>Puede crear un elemento html con id y luego acceder a él mediante document.getElementById() y establecer la propiedad innerText.
<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>Puede simplificar un poco el proceso utilizando fetch (que está integrado en Javascript) y agregando el contenido de su archivo en un elemento de su página:
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>