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
2 Answers
Reset to default 7This 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
版权声明:本文标题:html - Reading first line of a text file in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741443444a2379052.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论