Reading first line of a text file in javascript

柔情痞子 提交于 2019-12-19 09:38:17

问题


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?


回答1:


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



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


来源:https://stackoverflow.com/questions/12227729/reading-first-line-of-a-text-file-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!