【问题标题】:local html load txt file本地html加载txt文件
【发布时间】:2018-05-03 22:48:51
【问题描述】:

所以我使用本地 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 文件从文件中获取文本?

米切尔

【问题讨论】:

  • 你如何执行你的javascript?如果它在浏览器上,我认为它无法访问您的目录。
  • “本地”意味着您正在使用file:// 或某些“自定义类型”协议。因此,由于“安全限制”,它无法在 Chrome 和类似浏览器上运行。它应该可以在 Firefox 上运行:stackoverflow.com/a/38757037/4146962

标签: javascript html load offline


【解决方案1】:

这更像是一种解决方法,它涉及一些限制,但根据您的目标,它可能适合您的需求。或者不。

AFAIK 您将无法使用 XmlHttpRequest 实现此目的,但您可以使用 FileReader 加载文件。您可以在此 SO 中找到一个工作示例

How to open a local disk file with Javascript?


缺点是必须通过手动交互触发 FileReader。因此,如果没有用户 ( YOU ) 单击并浏览要加载的文件,您将无法加载文件。

你能解决吗?

如果是这样,那就更糟糕了,因为一旦加载完毕,只需将文件内容放入localeStorage,这样下次加载页面,或者刷新页面时,文件中的数据就可以来了来自 localeStorage,您不必手动选择要再次加载的文件。当然,除非文件已更改,但由于您不在服务器/网络服务器上,因此文件自动更改的可能性很低。所以我猜如果你必须手动更改文件,你也可以接受一次手动干预。

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage


如果您还没有选择,请考虑在文件和 localeStorage 中使用 JSON 格式的文本,它可以简化您的数据转换。


[编辑]当然,如果您的文件永远不会更改,只需将您的数据嵌入到 javascript 变量中。

[编辑 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>

【讨论】:

  • 谢谢。它响应用户操作很好。只是因为该文件是在某个时候创建​​的,然后在用户随身携带之前复制到该目录。我将如何将它添加到 javascript 变量中。而且它只是一个带有简单文本(小段落或几句话)的txt文件。
  • 我刚刚添加了一个示例
猜你喜欢
  • 1970-01-01
  • 2017-12-27
  • 2018-10-17
  • 2018-12-26
  • 1970-01-01
  • 1970-01-01
  • 2022-06-25
  • 2017-05-24
  • 1970-01-01
相关资源
最近更新 更多