Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

javascript - 如何读取本地文本文件?(How to read a local text file?)

I'm trying to write a simple text file reader by creating a function that takes in the file's path and converts each line of text into a char array, but it's not working.

(我正在尝试通过创建一个接受文件路径并将文本的每一行转换为char数组的函数来编写一个简单的文本文件阅读器,但是它不起作用。)

function readTextFile() {
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "testing.txt", true);
  rawFile.onreadystatechange = function() {
    if (rawFile.readyState === 4) {
      var allText = rawFile.responseText;
      document.getElementById("textSection").innerHTML = allText;
    }
  }
  rawFile.send();
}

What is going wrong here?

(这是怎么了?)

This still doesn't seem to work after changing the code a little bit from a previous revision and now it's giving me an XMLHttpRequest exception 101.

(从以前的版本中稍稍更改了代码后,这似乎仍然不起作用,现在它给了我一个XMLHttpRequest异常101。)

I've tested this on Firefox and it works, but in Google Chrome it just won't work and it keeps giving me an Exception 101. How can I get this to work on not just Firefox, but also on other browsers (especially Chrome)?

(我已经在Firefox上对其进行了测试,并且可以运行,但是在Google Chrome中它无法正常工作,并且一直给我一个异常101。如何使它不仅可以在Firefox上而且还可以在其他浏览器(尤其是Chrome)上运行)?)

  ask by Danny translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to check for status 0 (as when loading files locally with XMLHttpRequest , you don't get a status returned because it's not from a Webserver )

(您需要检查状态0(如使用XMLHttpRequest在本地加载文件时,不会返回状态,因为它不是来自Webserver ))

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

And specify file:// in your filename:

(并在文件名中指定file:// :)

readTextFile("file:///C:/your/path/to/file.txt");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...