Service request mode

Service request mode

Native Ajax

The native Ajax, XMLHtpRequest (XHR), uses the XMLHtpRequest object to asynchronously request data, so that the front end can asynchronously exchange data with the server. The data on a URL can be easily obtained through Ajax. XMLHtpRequest was originally designed by Microsoft, and then supported by Mila, Apple and Google (XMLHtpRequs) And incorporated into W3C standard.

function ajax(url, fnSucc, fnFaild) {
//Creating Ajax objects
    if (window.XMLHttpRequest) {
        var oAjax = new XMLHttpRequest();
    } else {
        var oAjax = new ActiveXObject("Microsoft.XMLHTTP");
    }
//Connect server
    oAjax.open('GET', url, true);
//send out
    oAjax.send();
//receive
    oAjax.onreadystatechange = function () {
        if (oAjax.readyState === 4) {
            if (oAjax.status === 200) {
                //alert('succeeded: '+ oAjax.responseText);
                fnSucc(oAjax.responseText);
            } else {
                //alert('failed ');
                if (fnFaild) {
                    fnFaild();
                }
            }
        }
    }
}

jQuery Ajax

As a lightweight library to improve the efficiency of JavaScript development, jQuery has a complete Ajax compatible suite. Its functions and methods allow us to load data from the server without refreshing the browser. jQuery Ajax is essentially the encapsulation of the original Ajax, and solves the compatibility problem. jQuery Ajax uses jsonp to implement cross domain requests. The code is as follows:

$.ajax({
    type: POST,
    url: url,
    data: data,
    dataType: dataType,
    success: function () {
    },
    error: function () {
    }
});

Axios

Axios is a client-side JS library for browsers and NodeJS. It is also a package for ES6 Promise mode to handle asynchronous operations. Axios is essentially a package of native XHR, but it is an implementation version of Promise and conforms to the ES6 specification.

Promise is a solution for asynchronous programming. ES6 writes it into the language standard, unifies the syntax, and provides promise natively

Axios is not native JS and needs to be installed. It can be used not only on the client, but also on the NodeJS client. Based on Promise object, Axios provides some interfaces for concurrent requests. It can easily call multiple asynchronous functions, intercept requests and responses, and cancel requests. The code is as follows:

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

Fetch

Fetch is actually an alternative to XMLHttpRequest. It is similar to the asynchronous operation of Ajax. It is a native request method implemented by the browser. As a relatively new technology, fetch will have browser compatibility problems. At present, Firefox 89 Fetch is already supported in version 0 and Chrome 87.0. Its implementation code is as follows:

fetch('/some/url',{
    method: 'get'
}).then(function(response){
   //Successful execution, processing results
}).catch(function(err){
//exception handling
});

//Chain processing
fetch('/some/url').then(function(response) {
  return;//Step 1 processing after successful request execution
}).then(function(retunedValue) {
//When step 1 is finished, proceed to step 2
}).cacth(function(errer) {
//exception handling
});

//await mode
try {
  let response = await fetch(ur);
  let data = response.json();
  console.log(data);
} catch(e) {
console.log("Oops, error",e);
}

Because the parameters passed by the GET() method are different from those passed by the POST() method during Fetch request, a simple Fetch can be encapsulated to unify the parameters of GET request and POST request. In practical application, it can be further encapsulated according to requirements to give better play to its advantages. The code is as follows:

/*Convert objects to a = 1 & B = 2
@param obj Parameter object*/
function obj2String(obj,arr=[],idx=0) {
  for (let item in obj) {
    arr[idx++]=[item.obj[item]]
  }
  return new URLSearchParams(arr).toString();
}

/* Real request
@param url Request address
@param options Request parameters
@param method Request mode*/
function commonFetcdh(url,options,method ='GET') {
const searchStr = obj2String(options);
let initObj= {}
if (method === 'GET') {
  url += "?" + searchStr
  initObj = {
    method: method,
    credentials: 'include'
  }
} else {
  initObj= {
    method: method,
    credentials: 'include',
    headers: new Headers({
      'Accept': 'application/json',
      'Content-Type': 'application/x-www-from-urlencoded',
    }),
    body: searchStr
  }
}      
fetch(url,initObj).then((res)=> {
    return res.json()
  }).then((res)=> {
  return res;
  })
}

/* GET request
@param url Request address
@param options Request parameters*/
function GET(url, options) {
   return commonFetcdh(url,options,'GET')
}

/*POST request
@param url Request address
@param options Request parameters*/
function POST(url,options){
   return commonFetcdh(url,options,'POST');
}

The code structure of Fetch is simpler than that of native Ajax, and the parameters are similar to jQuery Ajax. However, Fetch is a native JS API, separated from XHR, and is a new implementation in ES6 specification.

Keywords: Front-end axios JQuery Ajax fetch

Added by raghavan20 on Tue, 11 Jan 2022 17:49:09 +0200