1. Use ajax request
1. What is ajax request
Ajax
Right nowAsynchronous Javascript And XML
(asynchronousJavaScript and XML
), proposed in 2005, is a ‘new’ method of describing the use of a collection of prior art, including:HTML or XHTML, CSS, JavaScript, DOM, XML, XSLT
, and most importantlyXMLHttpRequest
. useAjax
Technical web applications can quickly present incremental updates on the user interface without overloading (refreshing) the entire page, which allows the program to respond to user actions faster.
2. Ajax request principle
-
A brief overview
Ajax
The principle ofJavaScript
NativeXmlHttpRequest
Objects send asynchronous requests to the server, obtain data from the server, and then useJavaScript
Come and operateDOM
, thereby achieving page update. -
Detailed interaction process with the server
- Create
Ajax
The core objectXMLHttpRequest
Object - pass
XMLHttpRequest
The object'sopen()
Method to establish a connection with the server - Build the data content required for the request and pass
XMLHttpRequest
The object'ssend()
Method sent to the server - pass
XMLHttpRequest
Provided by the objectonreadystatechange
Events, listen to the communication status of the server side - Accept and process the data results of the server's response to the client
- Operation according to the response results
DOM
, update the processing results toHTML
On the page
- Create
-
Detailed implementation code example
// Create XMLHttpRequest object const request = new XMLHttpRequest() // Listen to the onreadystatechange event and communicate with the server = function(e){ // Get the current request status. The value of readyState is 4, indicating that the entire request process is completed. if( === 4){ // Based on the returned status code, determine whether the current request is successfully returned if( >= 200 && <= 300){ // Get the result returned to the server () }else if( >=400){ // Get the error message returned from the server ("error message:" + ) } } } // The open() method of the XMLHttpRequest object establishes a connection with the server ('POST','http://xxxx') // Send the request to the server through the send() method of the XMLHttpRequest object ()
2. Use fetch request
1. What is a fetch request
Fetch
Request is a modernWeb API
, used inJavaScript
Issued inHTTP
Data request. It isXMLHttpRequest
An alternative to this, providing a more concise and modern way to handle network requests.Fetch
Functions are nativeJavaScript
Part of it, does not need to be usedXMLHttpRequest
Object.Fetch
Request to usePromise
to handle asynchronous operations, which makes its code clearer and more concise.
2. Fetch request principle
-
fetch
It is based on nativeXMLHttpRequest
Object to implement data requests. - at the same time,
fetch
Also based onPromise
Implement chained calls. - Implement
fetch
The essence: it is to realizeajax
Package andPromise
Implementation of .
By the aboveajax
In part of the explanation, we knowajax
Can be passedXMLHttpRequest
Simple implementation:
function ajax(url,suc,fail) { var xhr = new XMLHttpRequest(); ('POST',url, true); = function () { if( == 4){ if( == 200){ suc() } else { (err); fail(); } } }; (null); }
fetch can be implemented in simple combination with Promise and ajax:
function fetch(url) { return new Promise(function (resolve,reject) { ajax(url,function (res) { resolve(res); },function (err) { reject(err); }) }) }
The fetch call returns a Promise instance, which can directly call the then method and catch method of the Promise instance to obtain the request result or error information.
3. The difference between fetch and ajax
The main differences between Fetch and Ajax are their API design, syntax, error handling, progress monitoring, and processing of cross-domain requests.
- API design
- Fetch is an API in modern JavaScript. It uses Promise objects to handle asynchronous operations and can be called in chains to make the code easier to understand and maintain.
- Ajax is a traditional technology that usually uses XMLHttpRequest object to handle requests and responses.
- Syntax and error handling aspects
- Fetch uses a Promise-based API style, which returns a Promise object. For network request errors, 400 and 500 are considered successful requests and need to be encapsulated to process.
- The syntax of Ajax is relatively complex and requires writing more code to handle callback functions and states. It usually uses callback functions to handle asynchronous operations, which may lead to callback hell problems, especially in complex request chains.
- Progress monitoring
- Fetch has no way to natively monitor the progress of requests
- Ajax is based on native XHR development, which can be monitored
- Cross-domain requests
- Fetch has stricter restrictions on cross-domain requests because it follows a homologous policy. If cross-domain requests are required, appropriate CORS headers (Cross-Origin Resource Sharing) are required on the server side to allow cross-domain requests.
- Ajax is also restricted by homologous policies, but cross-domain requests can be made through technologies such as JSONP and proxy servers.
- Compatibility
Fetch is developed based on Promise, and Ajax is more compatible with Fetch.
Overall, Fetch is a modern and more flexible way to handle network requests, especially suitable for modern JavaScript applications, while Ajax is still used in some older applications and traditional environments, and may be easier to get started in some cases.
Summarize
This is the article about the ways to obtain resources in front-end (ajax, fetch) and its differences. For more related front-end resources in front-end, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!