Home >Web Front-end >HTML Tutorial >How to read txt file in html

How to read txt file in html

下次还敢
下次还敢Original
2024-04-05 10:36:201208browse

Reading TXT files in HTML requires the use of JavaScript's XMLHttpRequest object. Specific steps include: Create an XHR object Open the request and set the request type Set the response type Send the request Process the response After the request is completed, the onload event of the XHR object will be triggered, and the response content can be obtained.

How to read txt file in html

How to read TXT files using HTML

Reading TXT files in HTML requires JavaScriptXMLHttpRequest (XHR) object. The specific steps are as follows:

1. Create an XHR object

<code class="javascript">var xhr = new XMLHttpRequest();</code>

2. Open the request and set the request type

<code class="javascript">xhr.open('GET', 'path/to/text.txt');</code>

3. Set response type

<code class="javascript">xhr.responseType = 'text';</code>

4. Send request

<code class="javascript">xhr.send();</code>

5. Process response

After the request is completed, the XHR object's onload event fires. At this point you can get the response content:

<code class="javascript">xhr.onload = function() {
  var txt = xhr.response;
  // 对 txt 文本内容进行操作
};</code>

Sample 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>

Note:

  • Make sure that the TXT file matches The HTML file is located on the same domain name or CORS (Cross-Origin Resource Sharing) has been set up.
  • If the TXT file contains special characters, the response text may need to be escaped.

The above is the detailed content of How to read txt file in html. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn