Lesson 04-HTML5 HTTP Request Methods XMLHttpRequest API, Ajax and Fetch API

XMLHttpRequest API

XMLHttpRequest (XHR) is a browser built-in object that allows JavaScript to exchange data with the server without refreshing the page. It was first introduced by Microsoft in Internet Explorer 5, and was subsequently adopted by other browsers and standardized as a W3C recommended standard, becoming the core technology for implementing AJAX (Asynchronous JavaScript and XML).

Main features and usage:

Asynchronous communication: XMLHttpRequest supports asynchronous mode, so that the request and response process will not block the browser main thread, ensuring the smoothness of the user interface.

  • Cross-domain request: Through the CORS (Cross-Origin Resource Sharing) mechanism, XMLHttpRequest can initiate cross-domain requests to obtain data from different source servers.
  • Request method and status: Supports common HTTP methods (such as GET, POST, PUT, DELETE, etc.), and is set through the .open() method. The .send() method is used to send requests, and the .readyState attribute and .status attribute represent the request status and HTTP status code respectively.
  • Event-driven: By listening to the .onreadystatechange event handler, you can capture changes in the request status, and when .readyState is 4 (i.e. the request is completed), get the response data through .responseText or .responseXML.
  • Error handling: Use .status and .statusText to determine whether the request is successful or not, or use the .onerror event to handle errors.
const xhr = new XMLHttpRequest();
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Bearer your_token');
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.error('Request failed. Status:', xhr.status);
  }
};
xhr.send();

// Listen for status changes and responses
xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // Success status code
            console.log(xhr.responseText); // Or use xhr.responseXML, xhr.response (depending on the response type)
        } else {
            console.error('Request failed. Status:', xhr.status);
        }
    }
};

// Error handling
xhr.onerror = function() {
  console.error('An error occurred during the request.');
};

Cross-origin request

XMLHttpRequest supports cross-origin requests, but the server needs to configure the CORS (Cross-Origin Resource Sharing) policy to allow requests from specific sources. The browser will automatically add the necessary Origin header and follow the Access-Control-* header information returned by the server to process requests and responses.

Ajax

Ajax is not a specific technology or API, but a method of creating dynamic web applications using a series of related technologies (including XMLHttpRequest, HTML, CSS, JavaScript). Although it is called “XML”, in fact Ajax applications usually use JSON as the data exchange format because JSON is more convenient to process in JavaScript. The essence is still the asynchronous request method sent by XMLHttpRequest.

The core principle of Ajax is to use JavaScript to exchange data with the server in the background, so that part of the web page content can be updated without refreshing the entire web page. This breaks the traditional web application mode of “submit form → wait for server response → load new page”, and realizes partial refresh of the page and non-refresh data interaction.

Main features and application scenarios:

  • No refresh update: Ajax allows web pages to partially update content without refreshing the entire page, improving the user experience.
  • Dynamic interaction: Ajax enables asynchronous communication with the server, supporting scenarios such as real-time data update, dynamic form validation, online chat, map interaction, etc.
  • Page state management: Ajax can be used to implement complex state management of single-page applications (SPAs) without loading new HTML pages for each interaction.
  • Asynchronous communication: The most notable feature of Ajax is asynchronous processing. When a user triggers an action (such as clicking a button, scrolling a page, etc.), JavaScript sends a request to the server, while allowing the user to continue interacting with the web page without waiting for the server to respond. When the server returns the data, JavaScript processes the data in the background and updates the corresponding web page content.
  • Partial refresh: Through Ajax, web pages can only update part of the content instead of reloading the entire page. This greatly improves the user experience, reduces unnecessary network traffic, and avoids the sense of interruption caused by page jumps.
  • Data exchange format: Despite its name, modern Ajax applications prefer to use JSON as the data exchange format, because the natural affinity between JSON and JavaScript makes data parsing and processing easier. Of course, XML, HTML, and even custom formatted data can also be used for Ajax communication.
  • Front-end and back-end separation: Ajax promotes the separation of responsibilities between the front-end and the back-end. The front-end is responsible for user interface display and interaction logic, and exchanges data with the back-end API through Ajax; the back-end focuses on business logic processing and data provision, and returns structured data to the front-end.

Fetch API

Fetch API is a modern, Promise-based standard alternative introduced by HTML5 to replace the traditional XMLHttpRequest to implement network requests. Fetch API provides a simpler interface that is more in line with modern JavaScript development habits.

Main features and usage:

  • Promise basics: Return a Promise object, which is convenient for chain calls and exception handling using .then(), .catch(), and .finally().
  • Simple API: There is only one global function fetch(), which accepts URL and optional configuration object as parameters and returns Promise.
  • Richer response objects: The response object (Response) provides methods such as .json(), .text(), .blob(), .arrayBuffer() to parse different types of response data.
  • Better request/response control: Supports setting request headers, methods, cache strategies, credentials modes, etc., as well as handling various HTTP status codes and response streams.
  • Extensibility: The Fetch API provides a middleware mechanism for intercepting and modifying requests and responses (such as the Request parameter of fetch() and the Body type method of Response).
fetch('https://api.example.com/data', {
    method: 'POST', // request method, default is 'GET'
    headers: {
    'Content-Type': 'application/json', // set request headers
    },
    body: JSON.stringify({ key: 'value' }), // request body, applicable to methods such as 'POST', 'PUT'
    credentials: 'include', // control whether to send cookies, optional 'omit', 'same-origin', 'include'
    cache: 'no-cache', // cache policy, optional 'default', 'no-store', 'reload', 'no-cache', 'force-cache', 'only-if-cached'
})
// The Promise returned by fetch() will get a Response object when resolved. To access the response data, you need to call methods on the Response object, such as .json(), .text(), .blob(), and .arrayBuffer(), each of which returns a new Promise, which provides data of the corresponding type after parsing.
.then(response => {
    if (!response.ok) {
    throw new Error('Network response was not ok.');
    }
    return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Cross-origin requests

The Fetch API supports cross-origin requests, but requires the server to configure the CORS (Cross-Origin Resource Sharing) policy to allow requests from specific origins. The browser automatically adds the necessary Origin header and handles requests and responses in accordance with the Access-Control-* header information returned by the server.

Share your love