[英]How do I read a text file located in the same directory as my index.html using XMLHttpRequest() without using <input type=“file” id=“fileToLoad”>
I have my index.html and in the same directory I have a text file that I put there and want to be able to read it. 我有我的index.html,并且在同一目录中我有一个文本文件,我放在那里,希望能够阅读它。 Everything I have tried has failed except when using the input type format.
除了使用输入类型格式外,我尝试过的所有内容都失败了。 I don't need to do a file selection.
我不需要做文件选择。 I know what the file is and where it is.
我知道文件是什么以及它在哪里。
Here is my function: 这是我的功能:
<script type='text/javascript'>
document.getElementById("FunText").innerHTML =
"The text should show here:" + readTextFile('file:///E:/My_Html/list.txt');
function readTextFile(file)
{
var allText = "";
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function()
{
if(rawFile.readyState == 4)
{
if(rawFile.status == 200 || rawFile.status == 0) // status = 0
{
allText = rawFile.responseText;
alert("I get this:" + allText);
}
}
}
rawFile.send(null);
}
The variable allText always comes back empty. 变量allText总是返回空。 If I put "file:///E:/My_Html/list.txt" in the browser search box and it displays the contents of the file.
如果我在浏览器搜索框中输入“file:/// E:/My_Html/list.txt”,它会显示该文件的内容。 Does anyone see the problem?
有谁看到这个问题? I have tried rawFile.send(null), rawFile.send(), immediately after the open, at the end of the function.
我在函数结束时打开后立即尝试了rawFile.send(null),rawFile.send()。 Nothing works.
什么都行不通。 I have searched Stackoverflow, W3, and others.
我搜索过Stackoverflow,W3和其他人。 I am at a loss for ideas.
我不知所措。 Thank you for your patience and time.
感谢您的耐心和时间。
You could add the JQuery library to your project and use the $.get()
function: 您可以将JQuery库添加到项目中并使用
$.get()
函数:
http://api.jquery.com/jquery.get/ http://api.jquery.com/jquery.get/
Example (as the file is in the same level as the index.html): 示例(因为文件与index.html处于同一级别):
<script type='text/javascript'>
function readTextFile(file) {
$.get(file, function(data) {
document.getElementById("FunText").innerHTML = "The text should show here: " + data;
});
}
readTextFile("list.txt");
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.