[英]How do I implement my Javascript readTextFile?
概述:我一直在研究不需要filereader的文本文件读取方法。 我在“ /temp.txt”(绝对路径)处有一个名为temp.txt的文件,并且我一直在使用以下javascript函数尝试读取和打印出位于txt文件中的文本。
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");
}
我使用一个按钮来调用onclick函数,如下所示:
<button onclick="readTextFile('file:///temp.txt')">read the txt</button>
问题:当我单击按钮时,什么也没发生。 我尝试将“ file:///temp.txt”直接放入浏览器,并且浏览器设法正确打开了文本文件。 我实现的JavaScript错误吗? 我已经在Chrome浏览器中对此进行了测试。 提前非常感谢您!
更新1:我已经修复了代码上的一些错误,并获得了运行警报的代码,但是当它应该在警报(alert(allText);)中打印出文本文件时,它什么都不打印。
您可以在此处尝试代码: https ://jsbin.com/mucosavage/edit?html,输出只需将“ /temp.txt”更改为您具有的<button onclick="readTextFile('file:///temp.txt')">read the txt</button>
大多数浏览器实施安全限制,以防止通过XMLHttpRequest访问file://
URI。
除非用户通过<input type="file">
明确选择,否则应将本地文件系统上的文件视为禁止访问。
尝试以下方法:
<button onclick="readTextFile('file:///temp.txt')">read the txt</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.