자바스크립트 XMLHttpRequest 객체

The XMLHttpRequest object in JavaScript is widely used for making asynchronous HTTP requests to a server. It allows you to send data to and retrieve data from a server without having to refresh the entire web page. This makes it ideal for building responsive and dynamic web applications.

Getting started with XMLHttpRequest

To use the XMLHttpRequest object, you first need to create an instance of it:

let xhr = new XMLHttpRequest();

Next, you need to specify the HTTP method and the URL of the server you want to send the request to:

xhr.open('GET', 'https://api.example.com/data', true);

In the above example, the HTTP method is set to GET, and the URL is https://api.example.com/data. The third parameter true indicates that the request should be asynchronous.

Sending the request

After configuring the request, you can send it to the server:

xhr.send();

Optionally, you can send data along with the request by passing a string or a FormData object as an argument to the send() method.

Handling the response

To handle the response from the server, you need to set a callback function using the onreadystatechange event:

xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      let response = xhr.responseText;
      console.log(response);
    } else {
      console.error('Request failed with status ' + xhr.status);
    }
  }
};

In the above example, the callback function gets executed when the readyState changes. When the readyState becomes XMLHttpRequest.DONE (4), the response from the server is available. If the status code is 200, the request was successful, and the response can be accessed using responseText. Otherwise, an error message is logged.

Summary

The XMLHttpRequest object in JavaScript provides a powerful way to make HTTP requests. Its asynchronous nature allows for efficient and responsive web applications. By leveraging this object, you can communicate with servers, retrieve data, and update your web page without reloading it.

Note: With the introduction of the Fetch API in modern browsers, it is recommended to use the Fetch API for making HTTP requests instead of the XMLHttpRequest object. However, understanding the XMLHttpRequest object is still important as it is supported by all major browsers.