JS中如何将外部文件的内容加载到变量中

How to load content from external file in JS to variable

我想在不克隆 HTML 个文件的情况下制作一个简单的网站。

我想将内容存储在单独的文本文件(或 html)中的子目录(例如 pages/pagehome.txt、pages/pageabout.txt、pages/pagecontact.txt ).我使用了标签,但它不允许为嵌入的内容重复使用 css。

我想将该文件导入变量并通过 innerHTML 标签更改 divs。 如何将内容从该文件​​导入变量?我不想使用任何复杂的 API 或大量代码。

是否有仅使用 JS 将文件内容加载到变量的简单方法(没有 HTML 或像内容不可见 div 这样的方法)?

使用 XMLHttpRequest,并使用 onload 回调获取响应。

<body>
  <div id="divv"></div>
  <script>
    var txtFile = new XMLHttpRequest();
    txtFile.onload = function(e) {
      document.getElementById("divv").innerHTML = txtFile.responseText; 
    }
    txtFile.open("GET", "file.txt", true); 
    txtFile.send(null);
  </script>
</body>

编辑:看来你需要访问本地文件,所以你可以使用类似这样的东西

<body>
  <div id="divv"></div>
  <script>
    window.onload = function() {
        var iframe = document.createElement('iframe');
        iframe.id = 'iframe';
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
        iframe.src = 'file.txt';
        iframe.onload = function(){
            var text = document.getElementById('iframe').contentDocument.body.firstChild.innerHTML;
            document.getElementById('divv').innerHTML = text;
        };
    }
  </script>
</body>