Home > Web Front-end > JS Tutorial > How to Load a Local Text File into a JavaScript Variable?

How to Load a Local Text File into a JavaScript Variable?

Mary-Kate Olsen
Release: 2024-11-30 15:05:12
Original
120 people have browsed it

How to Load a Local Text File into a JavaScript Variable?

Loading Text File Contents into a JavaScript Variable

Question: How can we load the contents of a local text file (foo.txt) into a JavaScript variable, similar to doing so in Groovy?

Solution:

XMLHttpRequest (AJAX without XML) provides a way to retrieve remote resources asynchronously, enabling us to read the text file's contents via the following steps:

  1. Create an XMLHttpRequest Object:
    Start by creating a new XMLHttpRequest object.
var client = new XMLHttpRequest();
Copy after login
  1. Open and Send a GET Request:
    Open a GET request to the file's URL and trigger the sending process.
client.open('GET', '/foo.txt');
client.send();
Copy after login
  1. Handle the Response:
    Attach an event handler to the onreadystatechange event, which is constantly checking the state of the request.
client.onreadystatechange = function() {
  // Alert the responseText when the request is complete.
  if (client.readyState == 4 && client.status == 200) {
    alert(client.responseText);
  }
}
Copy after login

Alternative Option - jQuery:

While using XMLHttpRequest works, jQuery offers a more convenient interface for AJAX operations:

$.ajax({
  url: '/foo.txt',
  dataType: 'text',
  success: function(data) {
    console.log(data);
  }
});
Copy after login

Note:

For security reasons, this approach only allows loading files from the same domain as the application's origin.

The above is the detailed content of How to Load a Local Text File into a JavaScript Variable?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template