Ajax packaging

Time:2019-8-13

What is Ajax

AJAX is a technology that retrieves data from the server through the XMLHttpRequest object in JS and updates the content of the page without refreshing the page.

Packaging method

function ajax(params){

Affirm some necessary parameters, such as the successful callback function, error handling, url, data, type (http method), and do some bottom-up processing.

 const{
   success = () => {},
   error = () => {},
   type = 'get',
   data = {},
   url = '/'
} = params;

process

  1. Create asynchronous request objects

       const xhr =  new XMLHttpRequest()
  2. Register the callback when XHR sends the receive request and call the success or error function after the server returns the result

        xhr.onreadystatechange=function(){
          if(xhr.readyState===4){
            if(xhr.state===200){
              success(JSON.parse(xhr.responseText))
            }else{
              error(xhr.state,xhr.responseText)
            }
          }
        }
    let sendParams = '';
    Object. keys (data). map ((key) => {//Object. keys (object), get an array of attribute names in the object.  
        sendParams += `${key}=${data[key]}&`
    });
  3. Judging type

    • If it is get, the parameter is hung on the url, (url? SendParams), and send is empty.
    • If it is another type, the parameters are passed in send (sendParams), but the request header information needs to be set between open and send first.
      if(type==='get'){
        xhr.open(type,`${url}?${sendParams}`,true)
        xhr.send()
      }else{
        xhr.open(type,url,true)
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.send(sendParams);
        }
    }        

Call instance

    ajax({
        url: '/code/1',
        type: 'POST',
        data: {
            id: 'id',
            name: 'name'
        },
        success(result) {
            // do something
        },
        error(error1, error2) {
            // do something
        }
    })





Recommended Today

Manjaro uses SS method (requires nodejs environment)

Just installed manjaro, need to installshadowsocks-qt5+Proxy SwitchyOmega, but the latest Chrome has long blocked the installation of non Google store CRX channels. Here is my solution, which is troublesome but usable. If you are familiar with NPM commands in nodejs, you won’t find it troublesome, because nodejs is used for compilation. Preparation environment: A VPS […]