0

I have a plain text file stored at somewhere at a server to which i have the link. Now i want to read the file contents in a string var in my javascript code. Now I have written the code but does not know how to read the contents of the file.

I want to display the contents of the file in an alert box to the user, Can you please help.

var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() 
{
if (this.readyState == 4 && this.status == 200) 
    {

                                                          var parser=new DOMParser();
                                                          var xmlDoc = parser.parseFromString(xmlhttp.responseText,"text/html"); 

      }

 }
xmlhttp.open("GET",url, false);
xmlhttp.send();

Regards

3
  • why UI is reading backend file? can you request backend person to write a controller which reads the file and give response to UI Commented Jun 16, 2020 at 16:31
  • 1
    alert(xmlhttp.responseText) Commented Jun 16, 2020 at 16:33
  • normally the file content would be in the server response's body but it entirely depends on how the server is implemented Commented Jun 16, 2020 at 16:33

1 Answer 1

1

You can use the Fetch API like this:

fetch(url) // The default method is GET
  .then(res => res.text())
  .then(text => {
    alert(text);
  });

The Fetch API is generally preferred over XMLHttpRequest, however, if you want to continue using XHR:

const xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    alert(this.responseText);
  }
}
xmlhttp.open("GET",url, false);
xmlhttp.send();
Sign up to request clarification or add additional context in comments.

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.