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

Implementation of PHP Facades

Example <?php class RealRoute{ public function get(){ Echo’Get me’; } } class Facade{ public static $resolvedInstance; public static $app; public static function __callStatic($method,$args){ $instance = static::getFacadeRoot(); if(!$instance){ throw new RuntimeException(‘A facade root has not been set.’); } return $instance->$method(…$args); } // Get the Facade root object public static function getFacadeRoot() { return static::resolveFacadeInstance(static::getFacadeAccessor()); } protected […]