I'm new to JavaScript. I found an example to open local files with javascript on StackOverflow. After some googling, I'm able to set my Chrome to allow reading local files, and I am then able to run that example. However, I want to return the string allText
and use it later in my script. But the string become undefined
outside readTextFile()
.
There is a similar question here. It seems like it has something to do with the asynchronous feature of AJAX
. I can barely the understand the jargons at the moment. I just don't see why in this post the third parameter of XMLHttpRequest.open()
is set to be true
.
Anyway, below is my current code. I want to use allText
outside function readTextFile()
.
<!DOCTYPE html>
<html>
<script>
function readTextFile(file)
{
var allText;
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);
return allText; // this is the part that goes wrong I think
}
t = readTextFile("foo.file");
document.write(t) // print out "undeifned" instead of the correct answer
</script>
</html>