javascript Javascript从当前目录读取文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15615293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript read text file from current directory
提问by kklw
How to read text file (text1.txt) from current directory using javascript without jquery. I tried the following code.
如何在不使用 jquery 的情况下使用 javascript 从当前目录读取文本文件 (text1.txt)。我尝试了以下代码。
var file = "text1.txt";
var reader = new FileReader();
var result = reader.readAsText(file);
console.log(result);
回答by Quentin
The FileReader API is usually used to read files selected via the an <input type="file">
. It cannot read arbitrary files. The readAsText
methodexpects to receive with a Blob or a File object, not a string containing a file name.
FileReader API 通常用于读取通过<input type="file">
. 它无法读取任意文件。该readAsText
方法期望接收 Blob 或 File 对象,而不是包含文件名的字符串。
To read files that are siblings of the HTML document, use XMLHttpRequest. This will reliably work if you load the document over HTTP(S). If you are using a local HTML document (via a file:
URI) then security restrictions in many browsers will prevent it from working (and you should run a local web server instead).
要读取 HTML 文档的同级文件,请使用XMLHttpRequest。如果您通过 HTTP(S) 加载文档,这将可靠地工作。如果您使用的是本地 HTML 文档(通过file:
URI),那么许多浏览器中的安全限制将阻止它工作(并且您应该运行本地 Web 服务器)。
回答by Ivan Kuckir
Please distinguish 2 kinds of reading files:
请区分2种读取文件:
- reading "from internet" - use XMLHttpRequestto read any kind of file
- reading "from client" - use FileReader or
<input type="file">
- 读取“从互联网” - 使用XMLHttpRequest读取任何类型的文件
- 读取“从客户端” - 使用 FileReader 或
<input type="file">
回答by Ken H
You can include it in your javascript as a variable. Put this above your other script tag:
您可以将它作为变量包含在您的 javascript 中。把它放在你的另一个脚本标签之上:
<script src="text1.txt"></script>
edit your text1.txt file so it assigns all the content to a variable:
编辑您的 text1.txt 文件,以便将所有内容分配给一个变量:
gbl_text="...contents of my text file..."
+"...more contents..."
+"...and so on.... "
Then use the gbl_text variable in your javascript as needed...
然后根据需要在 javascript 中使用 gbl_text 变量...
function dosomething(){
//do stuff.....
alert(gbl_text)
}
回答by CACA COCHINA
make a tiny iframe. load the file there. read it with iframe.innerHTML
制作一个小小的 iframe。在那里加载文件。用 iframe.innerHTML 阅读它