Fernando
Fernando

Reputation: 1517

How to get file's content in Javascript without JQuery

Very often it is necessary to load contents from files that are stored in server into a Javascript variable or display it in a HTML element in order to accomplish some task inside a webpage.

How can I do that without relying in JQuery?

Upvotes: 0

Views: 2812

Answers (2)

Cameron637
Cameron637

Reputation: 1719

Try using fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

It's much easier to use than XMLHttpRequest.

Then, once you've fetched the resource, use insertAdjacentHtml to add it to the document body: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

i.e.

fetch("test.json")
  .then(function(response) {
           return response.json();
        })
  .then(function(json) {
           document.body.insertAdjacentHtml("afterbegin", "<p>" + json + "</p>);
        });
  .catch(function(error) {
             console.log('There has been a problem with your fetch operation: ' + error.message);
          });

Upvotes: 1

Fernando
Fernando

Reputation: 1517

One of the easiest ways I have found of doing that is by creating a function that gets a file and call's back another function when the download is ready. So in the example below, when the "test.txt" file content is loaded, it is displayed in a pre element.

<html>
<body>
<pre id="output"></pre>
</body>
<script type="text/javascript">

function get_file(url, callback)
{
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            callback(xmlhttp.responseText);
        }
    }
    xmlhttp.send();
}

get_file("test.txt", function(response)
{
    document.getElementById("output").innerHTML=response;
});

</script>
</html>

IMPORTANT

If you want to make your XMLHttpRequest synchronous, just change the line

xmlhttp.open("GET", url, true);

To

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

But it will come at the expense of hanging your webpage until the data is loaded.

Upvotes: 2

Related Questions