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. 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. If I put "file:///E:/My_Html/list.txt" in the browser search box and it displays the contents of the file. Does anyone see the problem? I have tried rawFile.send(null), rawFile.send(), immediately after the open, at the end of the function. Nothing works. I have searched Stackoverflow, W3, and others. 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:
http://api.jquery.com/jquery.get/
Example (as the file is in the same level as the 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.