XMLHttpRequest (XHR)
Principle
XMLHttpRequest (XHR) is a technology for asynchronous data exchange between the client and the server, which allows the browser to send an HTTP request to the server, get data and update part of the web page content without refreshing the entire page. XHR is a technology commonly used in modern web development for AJAX (Asynchronous JavaScript and XML) requests and data interaction.
The following is a detailed introduction to XMLHttpRequest:
-
Creating an XMLHttpRequest object: In JavaScript, an XMLHttpRequest object can be created by calling
new XMLHttpRequest()
. -
Set request parameters: Through the attributes and methods of the XMLHttpRequest object, you can set request parameters, including request method (GET, POST, etc.), request URL, asynchronous or not, request header information, request body, etc.
-
Sending a request: Initialize the request by calling the
open()
method of the XMLHttpRequest object, and send the request through thesend()
method. If it is a POST request, you can pass the request body data in thesend()
method. -
Monitor state changes: You can set the callback function for state changes through the
onreadystatechange
attribute of the XMLHttpRequest object. When the request state changes, the corresponding callback function will be triggered. -
Processing response: When the request returns successfully, you can get the HTTP status code through the
status
attribute of the XMLHttpRequest object, and get it through theresponseText
orresponseXML
attribute The data returned by the server. -
Asynchronous processing: Since XMLHttpRequest is an asynchronous request, after sending the request, other operations on the page will not be blocked, and other JavaScript codes can continue to be executed. Once the request is completed, the corresponding callback function will be triggered to process the response data.
-
Error handling: You can set the error callback function through the
onerror
attribute of the XMLHttpRequest object to handle the request failure or error. -
Cancel request: You can cancel the ongoing request by calling the
abort()
method of the XMLHttpRequest object.
The advantage of XHR is that it can fetch server data and update the page without refreshing the entire page, resulting in a smoother user experience. It is widely used in web development to implement functions such as dynamic content loading, form submission, and data interaction. However, it should also be noted that because XHR can request data across domains, security issues may be involved. Therefore, when using XHR, it is necessary to handle cross-domain requests carefully and prevent XSS attacks.
Usage
Example of a simple GET request using XMLHttpRequest:
// Create XMLHttpRequest object var xhr = new XMLHttpRequest(); // Set request parameters xhr.open('GET', 'https://api.example.com/data', true); // true means asynchronous request // listen for state changes xhr.onreadystatechange = function() {<!-- --> if (xhr.readyState === 4) {<!-- --> // request completed if (xhr.status === 200) {<!-- --> // return successfully console.log(xhr.responseText); // Get the data returned by the server } else {<!-- --> console.error('The request failed, status code:' + xhr.status); } } }; // send request xhr. send();
Example of POST request using XMLHttpRequest:
// Create XMLHttpRequest object var xhr = new XMLHttpRequest(); // Set request parameters xhr.open('POST', 'https://api.example.com/submit', true); // Set request header information (optional) xhr.setRequestHeader('Content-Type', 'application/json'); // listen for state changes xhr.onreadystatechange = function() {<!-- --> if (xhr.readyState === 4) {<!-- --> // request completed if (xhr.status === 200) {<!-- --> // return successfully console.log(xhr.responseText); // Get the data returned by the server } else {<!-- --> console.error('The request failed, status code:' + xhr.status); } } }; // send request var data = {<!-- --> name: 'John', age: 30 }; xhr.send(JSON.stringify(data)); // Send the request body data as a parameter
Since tool libraries such as fetch or axios are more commonly used in modern web development for network requests, XMLHttpRequest has been gradually abandoned, but it is still an important basic knowledge. Understanding its principles and usage helps to better understand modern network request technology.
fetch
fetch
is a modern API for network requests. It is based on Promise and provides a more concise and flexible way to send and process network requests.
Example of a GET request using fetch
:
// Send GET request fetch('https://api.example.com/data') .then(response => {<!-- --> if (!response.ok) {<!-- --> throw new Error('Network response was not ok'); } return response.json(); // parse the response data into JSON format }) .then(data => {<!-- --> console.log(data); // process the obtained data }) .catch(error => {<!-- --> console.error('Fetch error:', error); });
Example of a POST request using fetch
:
// Set request parameters var requestOptions = {<!-- --> method: 'POST', headers: {<!-- --> 'Content-Type': 'application/json' }, body: JSON.stringify({<!-- --> name: 'John', age: 30 }) // request body data as a parameter }; // Send a POST request fetch('https://api.example.com/submit', requestOptions) .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('Fetch error:', error); });
Advantages of fetch
:
- Using Promise supports chain calls, and the code is more concise and easy to read.
- By default, authentication information such as cookies will not be carried, avoiding potential security issues.
- Support for cross domain requests.
- Better handling of request errors.
It should be noted that fetch
may not automatically handle HTTP error status (such as 4xx and 5xx errors) like XMLHttpRequest in some cases, so you need to manually check the ok
attribute, and parse the response data through response.json()
, response.text()
and other methods.
While fetch
is the recommended usage for modern web development, compatibility issues also need to be considered. fetch
may not be supported in some old browsers, you can consider using polyfill or using other network request libraries (such as axios) to achieve similar functions.
The difference between XMLHttpRequest (XHR) and fetch
Both XMLHttpRequest
and fetch
are APIs for sending network requests on the front end, but they have some differences.
-
API design:
XMLHttpRequest
: is an old, event-based API that is relatively complicated to use and requires manual registration of event listeners to handle the results of asynchronous requests.fetch
: is a modern API based on Promise, which is more concise and easy to use, supports chain calls, and processes the results of asynchronous requests through thethen
method.
-
The request returns:
XMLHttpRequest
: The return value of the request is theXMLHttpRequest
object, and the response data needs to be obtained through attributes such asresponseText
orresponseXML
.fetch
: The return value of the request is aResponse
object, which needs to be passed throughresponse.json()
,response.text()
code> and other methods to parse the response data.
-
Cross domain request:
XMLHttpRequest
: When sending a cross-domain request, you need to set thewithCredentials
attribute totrue
to carry authentication information such as cookies.fetch
: By default, authentication information such as cookies will not be carried. If you want to send a cross-domain request and carry authentication information, you need to manually set thecredentials
option to'include'
.
-
Error handling:
XMLHttpRequest
: You need to manually check the status code and status information of the response, and handle errors through event handlers.fetch
: By default, it will only throw exceptions in case of network errors, and will not automatically handle HTTP error status (such as 4xx and 5xx errors). You need to manually check theok
attribute of the response, and then use methods such asresponse.json()
,response.text()
to parse the response data.
-
Promises support:
XMLHttpRequest
: does not support Promise, you need to use a callback function to process the result of the asynchronous request.fetch
: Promise is supported, and the results of asynchronous requests can be chained through thethen
method.
Since fetch
is a modern API, it is more concise and easy to use, and provides better Promise support. In new web development, it is recommended to use fetch
instead of XMLHttpRequest
. However, it should be noted that fetch
may not automatically handle HTTP error status like XMLHttpRequest
in some cases, and the status code and status information of the response need to be checked and processed manually .