4

Let's say I have a text file on my web server under /today/changelog-en.txt which stores information about updates to my website. Each section starts with a version number, then a list of the changes.

Because of this, the first line of the file always contains the latest version number, which I'd like to read out using plain JavaScript (no jQuery). Is this possible, and if yes, how?

SeinopSys
  • 8,787
  • 10
  • 62
  • 110

2 Answers2

7

This should be simple enough using XHR. Something like this would work fine for you:

var XHR = new XMLHttpRequest();
XHR.open("GET", "/today/changelog-en.txt", true);
XHR.send();
XHR.onload = function (){
    console.log( XHR.responseText.slice(0, XHR.responseText.indexOf("\n")) );
};
SeinopSys
  • 8,787
  • 10
  • 62
  • 110
Some Guy
  • 15,854
  • 10
  • 58
  • 67
2

So seeing as the txt file is externally available ie: corresponds to a URL, we can do an XHR/AJAX request to get the data. Note without jQuery, so we'll be writing slightly more verbose vanilla JavaScript.

var xmlHttp;

function GetData( url, callback ) {

    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = callback;
    xmlHttp.open( "GET", url, true );
    xmlHttp.send( null );
}

GetData( "/today/changelog-en.txt" , function() {

    if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 {

        var result = xmlHttp.responseText;
        var allLines = result.split("\n");

        // do what you want with the result 
        // ie: split lines and show the first line

        var lineOne = allLines[0];

    } else {
        // handle the error
    }
});
SeinopSys
  • 8,787
  • 10
  • 62
  • 110
Christopher
  • 1,358
  • 17
  • 32
  • Sorry, but Amaan's version is much more compact. That does not mean yours is bad, it's just that I like to do it the simpiest way possible. – SeinopSys Sep 01 '12 at 12:53
  • well its up to you, though, mine has the ability to re-use the code, and handle errors responsibly. – Christopher Sep 01 '12 at 12:54