In-depth analysis of XMLHttpRequest: a powerful tool for asynchronous communication

Article directory

  • introduce
  • What is XMLHttpRequest?
  • Basic usage of XMLHttpRequest
    • 1. Create an XMLHttpRequest object
    • 2. Configuration request
    • 3. Send request
  • XMLHttpRequest Attribute
    • send
    • readyState
    • status
    • statusText
    • response
    • responseText
    • responseType
    • responseURL
    • timeout
    • with Credentials
  • Asynchronous and synchronous requests
  • Request Types and Data Transfers
  • Debug example code
  • in conclusion

Introduction

In web application development, the XMLHttpRequest (XHR) method is a technique for sending HTTP requests to a server and receiving server responses. It provides developers with an easy and flexible way of communicating with servers using JavaScript. This blog will introduce in detail the usage and precautions of XMLHttpRequest, and debug and demonstrate through code examples.

What is XMLHttpRequest?

XMLHttpRequest is an object used in JavaScript to communicate with a server, send HTTP requests and get responses from the server. Through XHR, we can update part of the page content without refreshing the entire page to achieve dynamic interaction. XHR was originally designed for XML format data, but can also be used to transfer other data formats, such as JSON.

Basic usage of XMLHttpRequest

Using XMLHttpRequest, we can perform the following basic steps to send HTTP requests and process server responses:

1. Create XMLHttpRequest object

First, we need to create a new XHR object via the new XMLHttpRequest() constructor.

let xhr = new XMLHttpRequest();

2. Configuration request

Next, we configure the request using the open() method of the XHR object. The open() method accepts three parameters: request method, URL, and whether to use async. The request method can be GET, POST, PUT, DELETE, etc., the URL indicates the target address of the request, and the asynchronous parameter is a boolean value used to indicate whether the request is processed asynchronously (default is true).

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

3. Send request

After configuring the request, we use the send() method of the XHR object to send the request.

xhr. send();

XMLHttpRequest attribute

The following is a detailed explanation of some common attributes of XMLHttpRequest:

send

The send() method is used to send HTTP requests. It can be called after the open() method to send the request to the server. Depending on the request type and data transmission method, the parameters of the send() method will also vary.

  • For GET requests, parameters can be appended to the URL, set to null or omitted.
xhr.open('GET', 'https://example.com/api/data?param1=value1 & amp;param2=value2', true);
xhr. send();
  • For POST requests, parameters can be sent as the body of the request. You need to use the setRequestHeader() method to set the Content-Type of the request header, and send the parameters through the send() method.
xhr.open('POST', 'https://example.com/api/data', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('param1=value1 & amp;param2=value2');
  • For requests sent using the FormData object, you can directly pass the FormData object as the parameter of the send() method.
var formData = new FormData();
formData.append('param1', 'value1');
formData.append('param2', 'value2');

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

The send() method can also be used with other data formats and transports, such as sending JSON data or using response types such as arraybuffer. According to specific needs, you can choose an appropriate data transmission method and parameter format.

readyState

The readyState attribute represents the state of the XHR object, and it has the following values:

  • 0: Uninitialized, the open() method has not been called.
  • 1: Open, the open() method has been called, but the send() method has not been called yet.
  • 2: Send, the send() method has been called, but no response has been received yet.
  • 3: Received, part of the response data has been received.
  • 4: Done, all response data has been received.

status

The status attribute indicates the HTTP status code of the server response, such as 200 means success, 404 means not found, etc. Detailed status codes can be found in the HTTP specification.

statusText

The statusText attribute indicates the text description of the HTTP status code, such as “OK” means success.

response

The response attribute represents the data that the server responds to. Depending on the responseType, it can be a string, XML document, JSON object, etc.

responseText

The responseText attribute indicates that the server response data is returned as a string. (parsable via JSON)

responseType

The responseType attribute specifies the type of response data. It has the following values:

  • "" (empty string, default): returns a string.
  • "text": returns a string.
  • "arraybuffer": returns an ArrayBuffer object.
  • "blob": Returns the Blob object.
  • "document": Returns a Document object (XML or HTML).
  • "json": returns a JSON object.

responseURL

The responseURL attribute indicates the URL of the response returned by the server.

timeout

The timeout attribute indicates the timeout period of the XHR request, in milliseconds. A timeout event will fire if no response is received within the specified time.

withCredentials

The withCredentials property is a boolean value that indicates whether credentials (such as cookies and HTTP authentication) should be used when sending cross-origin requests.

Asynchronous and synchronous requests

XHR requests can be synchronous or asynchronous. Asynchronous requests are the default, and instead of blocking the execution of JavaScript code after the request is sent, a callback function is triggered after the server response comes back. Synchronous requests block the execution of JavaScript code until the server responds back. Synchronous requests should generally be avoided because they can cause the user interface to become unresponsive.

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

// Example of a synchronous request
xhr.open('GET', 'https://example.com/api/data', false);
xhr. send();

Request types and data transfer

XHR supports multiple request types, such as GET, POST, PUT, DELETE, etc. For GET requests, parameters can be appended to the URL; for POST requests, parameters can be sent as the body of the request. Here is an example of sending a POST request using XHR:

xhr.open('POST', 'https://example.com/api/data', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({<!-- --> key: 'value' }));,

In the above example, we use the setRequestHeader() method to set the Content-Type of the request header to application/json, and use the send() method to send a JSON formatted data

Debug sample code

Below are several common sample codes using XHR to help understand its usage and debugging process.

Initiate a GET request

xhr.open('GET', 'https://example.com/api/data', true);
xhr.onreadystatechange = function() {<!-- -->
  if (xhr. readyState === 4 & amp; & amp; xhr. status === 200) {<!-- -->
    var response = xhr. responseText;
    console. log(response);
  }
};
xhr. send();

Initiate a POST request

xhr.open('POST', 'https://example.com/api/data', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {<!-- -->
  if (xhr. readyState === 4 & amp; & amp; xhr. status === 200) {<!-- -->
    var response = xhr. responseText;
    console. log(response);
  }
};
xhr.send(JSON.stringify({<!-- --> key: 'value' }));

Process server responses

xhr.open('GET', 'https://example.com/api/data', true);
xhr.onload = function() {<!-- -->
  if (xhr. status === 200) {<!-- -->
    var response = JSON. parse(xhr. responseText);
    console. log(response);
  }
};
xhr.onerror = function() {<!-- -->
  console.log('Error occurred.');
};
xhr. send();

Conclusion

This blog introduces in detail the usage and precautions of the XMLHttpRequest method. Understanding the basic usage of XHR, asynchronous and synchronous requests, request types, and data transmission can help developers make better use of XHR for server communication and dynamic interaction. At the same time, we also emphasized important matters such as cross-domain requests, security considerations, and exception handling and error status codes. Through the debugging of code examples, readers can better understand and use XHR technology.