html怎么读取txt文件

  • 文章介绍
  • 热门推荐
  • 热门内容

如何使用 HTML 读取 TXT 文件

在 HTML 中读取 TXT 文件需要通过 JavaScript 的 XMLHttpRequest(XHR)对象。具体步骤如下:

1. 创建 XHR 对象

var xhr = new XMLHttpRequest();

2. 打开请求并设置请求类型

xhr.open('GET', 'path/to/text.txt');

3. 设置响应类型

xhr.responseType = 'text';

4. 发送请求

xhr.send();

5. 处理响应

请求完成后,XHR 对象的 onload 事件将触发。此时可以获取响应内容:

xhr.onload = function() {  var txt = xhr.response;  // 对 txt 文本内容进行操作};

示例代码

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 文件包含特殊字符,可能需要对响应文本进行转义处理。

以上就是html怎么读取txt文件的详细内容,更多请关注css网站其它相关文章!