在 html 中读取 txt 文件需要使用 javascript 的 xmlhttprequest 对象。具体步骤包括:创建 xhr 对象打开请求并设置请求类型设置响应类型发送请求处理响应请求完成后,xhr 对象的 onload 事件将触发,此时可以获取响应内容。
如何使用 HTML 读取 TXT 文件
在 HTML 中读取 TXT 文件需要通过 JavaScript 的 XMLHttpRequest
(XHR)对象。具体步骤如下:
1. 创建 XHR 对象
<code class="javascript">var xhr = new XMLHttpRequest();
2. 打开请求并设置请求类型
<code class="javascript">xhr.open('GET', 'path/to/text.txt');
3. 设置响应类型
<code class="javascript">xhr.responseType = 'text';
4. 发送请求
<code class="javascript">xhr.send();
5. 处理响应
请求完成后,XHR 对象的 onload
事件将触发。此时可以获取响应内容:
<code class="javascript">xhr.onload = function() {
var txt = xhr.response;
// 对 txt 文本内容进行操作
};
示例代码
<code class="javascript">var xhr = new XMLHttpRequest();
xhr.open('GET', 'path/to/text.txt');
xhr.responseType = 'text';
xhr.send();
xhr.onload = function() {
document.getElementById('txt-content').innerHTML = xhr.response;
};
注意:
- 确保 TXT 文件与 HTML 文件位于同一域名或已设置 CORS(跨域资源共享)。
- 如果 TXT 文件包含特殊字符,可能需要对响应文本进行转义处理。