在JavaScript中显示文本文件 [英] Display text file in JavaScript
本文介绍了在JavaScript中显示文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我应该使用什么代码来显示JavaScript中的纯文本.txt文件的内容?我希望文本在活动窗口的屏幕上滚动。
预先感谢!
解决方案 使用< pre> 或
< textarea>
,即 < pre id =contents>< / pre>
接下来,纯文本文件在哪里?
从服务器
函数populatePre(url){
var xhr =新的XMLHttpRequest();
xhr.onload = function(){
document.getElementById('contents')。textContent = this.responseText;
};
xhr.open('GET',url);
xhr.send();
}
populatePre('path / to / file.txt');
从本地计算机
用户使用< input type =file/>
<$选择文件c $ c>< input type =fileid =filechoice/>
然后当用户选择一个文件时,使用 FileReader 来填充< pre>
p>
document
.getElementById('filechoice')
.addEventListener(
'change',
function(){
var fr = new FileReader();
fr.onload = function(){
document.getElementById('contents')。textContent = this.result;
};
fr.readAsText(this.files [0]);
}
);
What code should I use to display the contents of a plain-text .txt file in JavaScript? I want the text to scroll on screen in the active window.
Thanks in advance!
解决方案
To get the text to display with new lines etc, use a <pre>
or a <textarea>
, i.e.
<pre id="contents"></pre>
Next is, where is the plain text file?
From a Server
Use XMLHttpRequest
function populatePre(url) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
document.getElementById('contents').textContent = this.responseText;
};
xhr.open('GET', url);
xhr.send();
}
populatePre('path/to/file.txt');
From the local machine
Make the user select the file using an <input type="file" />
<input type="file" id="filechoice" />
Then when the user selects a file, use FileReader to populate the <pre>
document
.getElementById('filechoice')
.addEventListener(
'change',
function () {
var fr = new FileReader();
fr.onload = function () {
document.getElementById('contents').textContent = this.result;
};
fr.readAsText(this.files[0]);
}
);
这篇关于在JavaScript中显示文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文