简体   繁体   中英

How do I implement my Javascript readTextFile?

Overview: I have been looking into ways of reading in a textfile without the need of filereader. I have a file called temp.txt located at "/temp.txt" (absolute path) and I have been using the following javascript function to try to read and print out the text located inside the txt file.

function readTextFile(file){
  alert("Debug 1");
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, true);
  rawFile.onreadystatechange = function ()
  {
      if(rawFile.readyState === 4)
      {
          if(rawFile.status === 200 || rawFile.status == 0)
          {
              var allText = rawFile.responseText;
              alert(allText);
          }
      }
  }
   rawFile.send(null);
   alert("Nothing");
}

I use a button that calls the function onclick like so:

<button onclick="readTextFile('file:///temp.txt')">read the txt</button>

The Problem: When I click the button nothing happens. I have tried putting "file:///temp.txt" directly into my browser and the browser manages to correctly open the text file. Am I implementing the javascript wrong? I have tested this in Chrome. Thank you so much in advance!

Update 1: I have fixed some bugs on my code and have gotten the code to run the alerts, but when its supposed to print out the textfile in the alert(alert(allText);) it prints out nothing.

Sources: Javascript - read local text file

You can try the code here: https://jsbin.com/mucosavage/edit?html,output just change the "/temp.txt" to something you have <button onclick="readTextFile('file:///temp.txt')">read the txt</button>

Most browsers implement security restrictions that prevent access to file:// URIs via XMLHttpRequest.

You should consider files on the local file system to be off-limits unless explicitly selected by the user via <input type="file"> .

尝试以下方法:

<button onclick="readTextFile('file:///temp.txt')">read the txt</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM