SoFunction
Updated on 2025-04-06

Detailed explanation of the way of obtaining resources in front-end (ajax, fetch) and their differences

1. Use ajax request

1. What is ajax request

AjaxRight 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. useAjaxTechnical 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

    AjaxThe principle ofJavaScriptNativeXmlHttpRequestObjects send asynchronous requests to the server, obtain data from the server, and then useJavaScriptCome and operateDOM, thereby achieving page update.

  • Detailed interaction process with the server
    • CreateAjaxThe core objectXMLHttpRequestObject
    • passXMLHttpRequestThe object'sopen()Method to establish a connection with the server
    • Build the data content required for the request and passXMLHttpRequestThe object'ssend()Method sent to the server
    • passXMLHttpRequestProvided by the objectonreadystatechangeEvents, 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 resultsDOM, update the processing results toHTMLOn the page
  • 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

FetchRequest is a modernWeb API, used inJavaScriptIssued inHTTPData request. It isXMLHttpRequestAn alternative to this, providing a more concise and modern way to handle network requests.FetchFunctions are nativeJavaScriptPart of it, does not need to be usedXMLHttpRequestObject.FetchRequest to usePromiseto handle asynchronous operations, which makes its code clearer and more concise.

2. Fetch request principle

  • fetchIt is based on nativeXMLHttpRequestObject to implement data requests.
  • at the same time,fetchAlso based onPromiseImplement chained calls.
  • ImplementfetchThe essence: it is to realizeajaxPackage andPromiseImplementation of .

By the aboveajaxIn part of the explanation, we knowajaxCan be passedXMLHttpRequestSimple 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!