在 html 中讀取 txt 文件需要使用 javascript 的 xmlhttprequest 對象。具體步驟包括:創(chuàng)建 xhr 對象打開請求并設置請求類型設置響應類型發(fā)送請求處理響應請求完成后,xhr 對象的 onload 事件將觸發(fā),此時可以獲取響應內(nèi)容。
如何使用 HTML 讀取 TXT 文件
在 HTML 中讀取 TXT 文件需要通過 JavaScript 的 XMLHttpRequest(XHR)對象。具體步驟如下:
1. 創(chuàng)建 XHR 對象
<code class="javascript">var xhr = new XMLHttpRequest();</code>
登錄后復制
2. 打開請求并設置請求類型
<code class="javascript">xhr.open('GET', 'path/to/text.txt');</code>
登錄后復制
3. 設置響應類型
<code class="javascript">xhr.responseType = 'text';</code>
登錄后復制
4. 發(fā)送請求
<code class="javascript">xhr.send();</code>
登錄后復制
5. 處理響應
請求完成后,XHR 對象的 onload 事件將觸發(fā)。此時可以獲取響應內(nèi)容:
<code class="javascript">xhr.onload = function() {
var txt = xhr.response;
// 對 txt 文本內(nèi)容進行操作
};</code>
登錄后復制
示例代碼
<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;
};</code>
登錄后復制
注意:
確保 TXT 文件與 HTML 文件位于同一域名或已設置 CORS(跨域資源共享)。
如果 TXT 文件包含特殊字符,可能需要對響應文本進行轉(zhuǎn)義處理。






