0

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?

2
  • append a <p> tag as a child of the header element with the text you want inside of the <p> tag. Commented Jun 11, 2019 at 17:05
  • Why not use a json file, read it and parse the data to a JS object? Much simpler and elegant solution. Commented Jun 11, 2019 at 17:10

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.