I want to use a text file as source for the text on my website. I just can't display it where I want it to be
I have already managed to read the text from the file, but now I'm stuck.
This is my readFile function:
<script>
function readFile(input){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var textFileText = searchFile(this.responseText, input);
document.getElementById(input).innerHTML = this.textFileText;
}
};
xhttp.open("GET", textFile, true);
xhttp.send();
}
</script>
I've tried it out and it works.
This is the searchFile function:
<script>
function searchFile(text, searched){
var output;
var n = text.search(searched);
output = text.substr((n+str.length+2), text.indexOf('\n'));
return output;
}
</script>
It's supposed to filter the text in the file for a specific word.
The text file looks like this:
[header]=text
[thing1]=more text
My idea is that if I call the function like this:
readFile("thing1");
The output should be "more text"
Here I call the function to display the header Text:
<h2 onload = "readFile(this.id)" id = "header"></h2>
But then nothing gets displayed.
I've also tried this:
<h2 onload = "readFile('header')" id = "header"></h2>
But again nothing is displayed.
Am I missing something or did I do something wrong?
There is no onload
for h2
or most tags for that matter. So instead of calling the function from the onload
, I would simply call the function from within script tags on the page.
<script>readFile('header');</script>
The only error I detected in your code is the misuse of variable =>
<script>
function searchFile(text, searched){
var output;
var n = text.search(searched);
//output = text.substr((n+str.length+2), text.indexOf('\n'));
output = text.substr((n+searched.length+2), text.indexOf('\n'));
return output;
}
</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.