Html 在 JavaScript 中显示文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18933085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display text file in JavaScript
提问by Vedant Chandra
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.
我应该使用什么代码在 JavaScript 中显示纯文本 .txt 文件的内容?我希望文本在活动窗口的屏幕上滚动。
Thanks in advance!
提前致谢!
采纳答案by Paul S.
To get the text to display with new lines etc, use a <pre>
or a <textarea>
, i.e.
要使用新行等显示文本,请使用 a<pre>
或 a <textarea>
,即
<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" />
<input type="file" id="filechoice" />
Then when the user selects a file, use FileReaderto populate the <pre>
然后当用户选择一个文件时,使用FileReader来填充<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]);
}
);
回答by avngr
We can use below code for this purpose:
为此,我们可以使用以下代码:
<iframe src="http://dev.imaginestudios.cu.cc/test.txt"></iframe>