admin管理员组

文章数量:1290186

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?

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?

Share Improve this question edited Feb 3, 2016 at 13:29 SeinopSys asked Sep 1, 2012 at 12:30 SeinopSysSeinopSys 8,93710 gold badges65 silver badges114 bronze badges 7
  • is the file available externally? ie: can it be reached via an XHR/AJAX request? – Christopher Commented Sep 1, 2012 at 12:31
  • Don't know anything about AJAX. – SeinopSys Commented Sep 1, 2012 at 12:33
  • Would you hypothetically be able to provide a url that would result in the txt file in question? If so I can show you what code to write to achieve the results you're looking for. – Christopher Commented Sep 1, 2012 at 12:36
  • cool, then we can just make a XHR request, will post an answer now. – Christopher Commented Sep 1, 2012 at 12:37
  • @DJDavid98: Is your website hosted on hunpony.hu? – Eric Commented Sep 1, 2012 at 12:44
 |  Show 2 more ments

2 Answers 2

Reset to default 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")) );
};

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
    }
});

本文标签: htmlReading first line of a text file in javascriptStack Overflow