Search code examples
javascripthtmlfilefileapi

Open a text file from server on the Client-side using Javascript


No matter how much I look this up all I get is the w3C File API which focuses on local files for the client.

What I'm trying to do is I have a server. I'm trying to use client-side javascript to grab the server hosted text file, a.txt, and display it to the innerDOM of an html page. My server directory look like this:

  • index.html
  • read.js
  • text files
    • a.txt

All I want to have happen is for, on the client side, the javascript read.js running in the index.html on onload to display the contents of a.txt. I figure that since a.txt will never be large, leaving it to the client is fine. But I can't figure out how to do this and the W3C File API isn't offering me answers.

If I had to guess, somehow making sure index.html loads a.txt and then grabbing that via the file API might be the way to go but I'm not sure how to do that.

And I'll admit it, I'm a bit of a noob. If I'm invalidating browser sandbox or doing something impossible, please tell me. I just thought this would be so simple.

Also, I'd appreciate that if you were going to suggest AJAX, either don't, or explain it like I'm a baby because I really don't know.

Thank you all so much for your help.


Solution

  • Why file API is irrelevant:

    Web applications should have the ability to manipulate as wide as possible a range of user input, including files that a user may wish to upload to a remote server or manipulate inside a rich web application.

    From W3C File API.

    So, File API is intended to be used to allow users to upload files from their clients into the server. On the other hand, AJAX is used to allow users to download files and other data from the server into their clients. And this is exactly what you need.

    Refer to jQuery's ajax documentation.