编程知识 cdmana.com

Front and back end data interaction (III) -- Ajax encapsulation and call

There are many frameworks that have ajax encapsulation , Just call it when you need it , such as jquery Is the most commonly used . Why do we need to learn ajax The packaging? ? First, strengthen our understanding of ajax The understanding of , Second, if it's just because ajax The request needs to be introduced into the framework , We can encapsulate one by ourselves , This eliminates the need to introduce redundant frameworks .

One 、 Packaging considerations

Encapsulation is to make the same parts common , Save resources , Improve code reusability , Work efficiency is also high , Therefore, different parameter event types need to be passed in through the call , I need to pay attention to :

1.1、 The ginseng

send out ajax When asked , The main parameters are :

  • request url
  • Request type
  • Request parameters
  • Successful callback
  • Failed callback
  • Timeout time

The above six parameters must be set to be dynamically passed in , Easy to control arbitrary ajax request . The timeout can be set uniformly , If it is used as a parameter, it is more convenient to control the timeout of any request .

1.2、 Request types are processed separately

The request types are get and post Two kinds of ,get When a type passes a value , Data follow url After the address ,post Carry in the request body when transmitting value , You also need to set the request data type . Therefore, we need to judge and deal with them separately .

if(type == 'GET'){
 xhr.open( 'GET' , url+'?'+strData , true )
 shr.send()
}else{
 xhr.open('POST',url,true)
 xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
 xhr.send( strData )
}

1.3、 Request timeout processing

When the network service or interface is abnormal , The request was sent without response , The page will not respond , A global timeout is required , When the time out has not returned , Auto end request , Return exception .

The syntax is as follows :

// Set the time to 2s
xhr.timeout = 2000 ;
// Timeout callback 
xhr.ontimeout = function(){
 console.log(' Network anomalies , Try again later ')
}

1.4、 Error handling

Network interruption , When the request cannot be sent to the server , Request failures need to be handled . Use onerror Event handling .

The syntax is as follows :

xhr.onerror = function(){
 console.log(" Network anomalies , Please check the network ")
}

Two 、 encapsulation ajax Code

according to ajax Request flow , The encapsulation code is as follows : Easy to use later , Recommended collection .

function ajax(option) {
 // method, url, data, timeout, success, error
 var xhr;
 var str = data2str(option.data);
 if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
 }else {
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
 }
 if (option.type.toLowerCase() === 'post') {
  xhr.open(option.type, option.url, true);
   xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   xhr.send(str);
  } else if (option.type.toLowerCase() === 'get') {
   xhr.open(option.type, option.url + '?' + str, true);
   xhr.send();
  }
 xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
   clearTimeout(timer);
   if (xhr.status >= 200 && xhr.status < 300 || xhr === 304) {
    option.success(xhr);
   }else {
    option.error(xhr);
   }
  }
 };
 if (option.timeout) {
  var timer = setTimeout(function () {
   xhr.abort();
   clearTimeout(timer);
  }, option.timeout)
 }
}
//  Converts an object to a string for transmission 
function data2str(data) {
 var res = [];
 data.t = new Date().getTime();
 for (var key in data) {
  res.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
 }
 return res.join('&');
}

The calling code is as follows :

ajax({
  method:'GET',
  url:'1.txt',
  data:{
   // Request data 
  },
  timeout:2000,
  success:(res)=>{
   console.log(' Successfully returns ',res.response)
  },
  error: err => {
   console.log(' error message ',err)
  }
 })

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

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

Scroll to Top