簡體   English   中英

本地html加載txt文件

[英]local html load txt file

所以我正在使用本地html和javascript文件作為視頻文件的gui。 這幾乎是我的服務器index.php的外賣版本,它們可以在其他地方使用。 一切正常,但我正在嘗試從txt文件加載內容。 我的網絡服務器使用XMLHttpRequest來檢索它,因為它是服務器端。 但是由於外賣版本不在服務器上,因此文本文件與html文件位於同一本地目錄中

function loadBookmarks(){
  var infoDoc = new XMLHttpRequest()
  infoDoc.open("GET","info.bk");
  infoDoc.send();
  infoDoc.onreadystatechange = function() {
    if (infoDoc.readyState== 4 && infoDoc.status == 200) {
        document.getElementById("bookmarks").querySelector('p').innerHTML = infoDoc.responseText;
        document.getElementById("infoButton").style.backgroundColor = "#119933";
    } else {
        document.getElementById("bookmarks").querySelector('p').innerHTML = "";
        document.getElementById("infoButton").style.backgroundColor = "#993333"
    }
 }  
}

那就是我正在使用的功能。 還有另一種方法可以使用非服務器離線javascript文件從文件中獲取文本嗎?

米切爾

這是一種解決方法,涉及一些約束,但根據您的目標,可能會滿足您的需求。 或不。

AFAIK您將無法使用XmlHttpRequest實現此目的,但可以使用FileReader加載文件。 您可以在此SO中找到一個有效的示例

如何使用Javascript打開本地磁盤文件?


缺點是FileReader必須從手動交互中觸發。 因此,如果沒有用戶(YOU)單擊並瀏覽要加載的文件,您將無法加載文件。

你能應付嗎?

如果是這樣,那就更糟了,因為一旦加載完畢,只需將文件內容放入localeStorage中即可,因此下次加載頁面或刷新頁面時,文件中的數據可能來自localeStorage ,您無需手動選擇要再次加載的文件。 當然,如果文件已更改,但您不在服務器/ Web服務器上,則文件自動更改的可能性很小。 因此,我想如果您必須手動更改文件,則還可以接受另一種手動干預。

https://developer.mozilla.org/zh-CN/docs/Web/API/Window/localStorage


如果還不是您的選擇,請考慮在文件和localeStorage中使用JSON格式的文本,它可以簡化您的數據轉換。


[編輯]當然,如果您的文件永不改變,只需將數據嵌入到javascript變量中即可。

[EDIT 2]示例

<body>
    <!-- The input widget to select a file from browse -->
    <input type="file" id="file-input" />

    <!-- testing purpose only, a markup to display the loaded file content -->
    <h3>Loading a file:</h3>
    <pre id="file-content"></pre>
    <script>

    // Place a listener to know when the page is loaded
    window.addEventListener('load',function(e){
      // If there is some persistent data on the browser called 'stored_data'
      if( localStorage.getItem('stored_data')){
        // We can do something with this data
        // without asking a user interaction at first
        // User interaction could be done in order to refresh the data ( file changed since storing in browser cache )
        doSomethingWithFileContents();
      }
    });

    /**
     * This is the callback of the addEventListener, it will be executed each time user select a file
     * It's linked below, on the addEventListener call
     */
    function readSingleFile(e) {
      //retrieve the first selected file the user has select
      var file = e.target.files[0];

      // If no file selected, abort this function execution
      if (!file) {
        return;
      }
      // If a file is selected, create a new file reader
      var reader = new FileReader();

      // Define a callback to be run when the file will be loaded
      reader.onload = function(e) {

        // You can still use some console.log for debugging purpose
        //console.log(e);

        // Retrive the content of the loaded file
        var contents = e.target.result;

        // To enable some persistency, store the contents into a localeStorage
        // It means next time you load the page, the data could come from the browser cache
        localStorage.setItem('stored_data', contents );

        // Will can now call the logic what we need to do with the file content
        doSomethingWithFileContents();
      };

      // Trigger the file reader to load the selected file
      reader.readAsText(file);
    }

    /**
     * This function will be executed when data is ready.
     * You should implements the logic that should be run with the file data
     *
     *  - Data is ready could mean:
     *      - Data was available through localStorage
     *      - Data has just been loaded through FileReader
     */
    function doSomethingWithFileContents() {

      // Retrieve the cached data
      var loadedData = localStorage.getItem('stored_data');

      // Get the element that will display the raw data
      var element = document.getElementById('file-content');
      // Set its content to the storedData
      element.textContent = loadedData;

      // Once again, I strongly recommend you to use JSON formatted value in the file
      // It will enable some easy transformation/parsing from js side


    }

    // Place a addEventListener on the file-input id element
    // When its value changed, run the readSingleFile function
    document.getElementById('file-input').addEventListener('change', readSingleFile, false);
</script>
</body>

暫無
暫無

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

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