编程知识 cdmana.com

Front and back end data interaction (VI) -- advantages, disadvantages and comparison of Ajax, fetch and Axios

One 、ajax、fetch and axios brief introduction

1.1、ajax

ajax Is the first technology to send back-end requests , Belongs to the original js .ajax Use the source code , Please click on 《 Native ajax Ask for detailed explanation 》 see . Before general use , We all need to encapsulate them , So jQuery Of ajax For example .

Packaged ajax as follows :

const $ = {};
$.ajax = (obj)=>{
 var xhr;
 if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
 } else if (window.ActiveXObject) { // IE
  try {
   xhr = new ActiveXObject('Msxml2.XMLHTTP');
  } catch (e) {
   try {
    xhr = new ActiveXObject('Microsoft.XMLHTTP');
   } catch (e) {}
  }
 }
 if (xhr) {
  xhr.onreadystatechange = () =>{
   if (xhr.readyState === 4) {
    if (xhr.status === 200) {
     obj.success(xhr.responseText); // Return value transmission callback
    } else {
     //failcallback
     obj.error('There was a problem with the request.');
    }
   } else {
    console.log('still not ready...');
   }
  };
  xhr.open(obj.method, obj.url, true);
  //  Set up  Content-Type  by  application/x-www-form-urlencoded
  //  Transfer data in the form of a form 
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send(util(obj.data));// Handle body data 
 }
// Processing data 
 const util = (obj)=>{
 var str = ''
 for (key in obj){
  str += key +'='+obj[key]+'&'
  }
  return str.substring(0,str.length-1)
 }    
}

Encapsulation is complete , When you start using it, you will find ,body and header A little messy , And the problem of going back to hell , So we have a new fetch Request Technology .

1.2、fetch

fetch First, we solved the problem of callback to hell , The result he returned was a Promise object , Yes Promise Unfamiliar can click 《Promise Detailed explanation 》.

fetch Use as follows :

fetch(url,options).then(response=>{
// handle HTTP response
},error=>{
// handle network error
})

fetch When sending a network request , Any data format can be transmitted , It's very simple . however fetch timeout 、 Termination cancellation is inconvenient , You can only cancel Promise To complete , If there are more than one fetch When asked , It's harder to deal with . besides ,fetch It's a relatively new technology , Lower version browsers and IE Poor browser support .

1.3、axios

axios Very powerful , Include Cancel the request , timeout handler , Progress processing, etc . But its essence is still ajax, be based on Promise encapsulate , Both solve the problem of callback hell , It can also well support various browsers .

axios The usage code is as follows :

axios.post('/user', {
 firstName: 'Fred',
 lastName: 'Flintstone'
})
.then(function (response) {
 console.log(response);
})
.catch(function (error) {
 console.log(error);
});

Two 、ajax、fetch、axios Advantages and disadvantages

2.1、ajax Advantages and disadvantages :

  • Belong to js Native , be based on XHR Development ,XHR Unclear structure .
  • in the light of mvc Programming , Because recently vue and React The rise of , Do not conform to the mvvm Front end development process .
  • Just use ajax encapsulation , The core is to use XMLHttpRequest object , Use more and in order , It's easy to cause a callback to hell .

2.2、fetch Advantages and disadvantages :

  • Belongs to the original js, Divorced from xhr , Claim to be able to replace ajax technology .
  • be based on Promise Object design , It can solve the problem of callback to hell .
  • Provides a wealth of API, Simple structure .
  • Default without cookie, You need to set .
  • There is no way to detect the progress of the request , Unable to cancel or timeout processing .
  • The return is Promise object , There are many ways to get results , Data types have corresponding acquisition methods , Packaging needs to be handled separately , Error prone .
  • Browser support is poor .

2.3、axios Advantages and disadvantages :

  • Create in browser XMLHttpRequest request , stay node.js Created in http request .
  • Solve the problem of callback to hell .
  • Automatically convert to json data type .
  • Support Promise technology , Provide concurrent request interface .
  • The progress can be detected through the network request .
  • Provide timeout processing .
  • Good browser compatibility .
  • There's an interceptor , Request and response can be handled uniformly .

Link to the original text : https://www.cnblogs.com/web-learn/p/15249874.html

版权声明
本文为[stupid]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/10/20211002145421670V.html

Scroll to Top