在 html 正文中显示文本文件内容:如何在我可以在 HTML 正文中显示的变量中获取 XMLHttpRequest 的结果?

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

我已经解决这个问题好几个小时了。 我的 objective 是加载一个远程文本文件的内容,并在 HTML 内部以样式显示它(所以“嵌入”不是我很快发现的解决方案)。我尝试了几段代码并进行了 100 多次测试。除了一个问题,我设法解决了所有问题。即使我可以获取文件的内容,甚至可以在控制台中打印它,我也无法将其存储在可以嵌入到 HTML 正文代码中的变量中。以下是我到目前为止的位置。感谢您的帮助。

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>

您可以创建一个带有 id 的 html 元素,然后通过 document.getElementById() 访问它并设置 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>

您可以使用 fetch(内置于 Javascript)并将文件内容添加到页面上的元素中,从而稍微简化此过程:

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>