Muccagelato Muccagelato - 3 months ago 7
HTML Question

change p content with text file one

I'm coding my first website, now I'm trying to change a p content with the content of some text files, which contains long descriptions of what my site is about, actually I've tried many ways, like httprequest(), FileReader() and jquery get, but actually I haven't managed it,because I was running it locally and probably because of the wrong file position, so i created a new small code in witch I tried jquery get, I ran it on "web server for chrome" but it doesn't work.

this is the code:

<!DOCTYPE html>
<html>
<body>

<div><h2 id="demo">Lets change this text</h2></div>

<button type="button" onclick="loadDoc()">Change Content</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
function loadDoc() {
$.get("hello.txt",function(data){
getElementById('demo').innerText= data;
});
}
</script>

</body>
</html>


when I load it, the p and the button are displayed, but when I click the button nothing happens; the .html and the .txt files are in the same folder.
I'have been stuck on it for many days, please help, and don't mark it as duplicate.

any help is appreciate.

Answer

You could try this out

<script>
function loadDoc() {
    $.get("hello.txt",function(data){
    document.getElementById('demo').innerHTML= data;
  });
 }

</script>

HTML:

 <div><h2 id="demo">Lets schange this text</h2></div>

    <button type="button" onclick="loadDoc()">Change Content</button>
<button type="button" onclick="loadDocWithHttp()">Change Content from Http request</button>

Using AJAX:

function loadDocWithHttp() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("demo").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET", "hello.txt", true);
  xhttp.send();
}
Comments