簡體   English   中英

如何將JS中的外部文件中的內容加載到變量中

[英]How to load content from external file in JS to variable

我想在不克隆 HTML 文件的情況下制作一個簡單的網站。

我想將內容存儲在子目錄(例如 pages/pagehome.txt、pages/pageabout.txt、pages/pagecontact.txt)中的單獨文本文件(或 html)中。 我使用了標簽,但它不允許為嵌入的內容重用 css。

我想將該文件導入變量並通過 innerHTML 標記更改 div。 如何將內容從該文件導入變量? 我不想使用任何復雜的 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM