I am trying to read in the text from a file and store it as a variable in javascript. Being new to JS, I had no idea this would be so difficult.
First I start an http server with python
python -m http.server
which runs at http://localhost:8000
.
Then I am including the following script in my HTML. My plan is to store the text in a hidden <p>
element and then access it later in the script. Because the script runs asynchronously, when I get the element's HTML it is still be initial stuff.
<script>
function readTextFile(file){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function (){
// Wait until file has loaded (state 4)
if (rawFile.readyState == 4) {
var text = rawFile.responseText;
var e = document.getElementById("myFileText");
e.innerHTML = text;
console.log('inside');
}
}
rawFile.send(null);
};
readTextFile('http://localhost:8000/static/live-slideshow/image_paths.txt');
// The following line results in console output of the old internals
var text = document.getElementById("imagePaths").innerHTML
console.log(text)
// Remaining script that uses the "text" variable...
</script>
My questions are:
- how can I tell the script to "wait until the readTextFile function has run" before continuing
- am I doing this all wrong? (I am only looking to host this thing locally - on my raspberry PI actually)
This is a problem I could solve with Flask or a similar framework but I want to make this as lightweight as possible (preferably no jQuery - but that being said, a nice solution with $'s would still be welcome!)