如何读取本地文本文件? [英] How to read a local text file?
问题描述
我试图通过创建一个接受文件路径的函数来编写一个简单的文本文件读取器,并将每一行文本转换为一个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();
$ / code>
这里出了什么问题?
从以前的版本开始稍微更改一些代码,现在看起来还不行它给了我一个 XMLHttpRequest
例外101.
我已经在Firefox上测试过了,它可以工作,但是在Google铬它不会工作,它不断地给我一个例外101.我怎样才能得到这个工作不只是Firefox,但也在其他浏览器(特别是铬)?
您需要检查状态0(在本地使用 XMLHttpRequest
加载文件时,不会返回状态因为它不是来自 Web服务器
)
$ p $函数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);
然后指定 file://
$ $ $ $ $ $ $ $ readTextFile(file:/// C:/ your / path / to / 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.
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.
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)?
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
)
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:
readTextFile("file:///C:/your/path/to/file.txt");
这篇关于如何读取本地文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!