Ajax native

Time:2019-11-21

The full name of AJAX is “asynchronous JavaScript and XML”

Ajax actually refers to asynchronous JavaScript and XML. It is a web page development technology for creating interactive web page applications. Simply speaking, it can make web pages achieve asynchronous updates

Four steps of Ajax request

  • Request initialization
    let xhr = new XMLHttpRequest();
  • Establish connection
Xhr.open (request method, address, true) default true asynchronous request method get parameter is bound after the address post parameter is put in the send() method
  • Send out
XHR. Send() // parameters in post XHR. Send (parameter) send can only be strings
  • Monitoring response
xhr.onreadystatechange=()=>{
                //ReadyState 0: initialize request 1: establish connection 2: the request is sent successfully 3: the server receives your request and processes 4: the server returns data and ends the response
                if(xhr.readyState ===4){
                    //Status status 200 succeeded
                    if(xhr.status===200){
                        //Data returned to you by xhr.responsetext server
                        // console.log(xhr.responseText)
                    }
                }
            }

Note: if the request mode is post, you need to set the request header

    xhr.setRequestHeader("content-type","application/json") application/x-www-form-urlencoded

Compatible with IE

function createXml(){
        let xmlHttp;
        if (window.XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        }Else if (window. Activexobject) {// IE compatible
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return xmlHttp;
    }

Ajax encapsulation

function ajaxFn(type,url,data){
        //Request initialization create request body
        let xhr = new XMLHttpRequest();
        // let xhr = createXml();
        //Set request mode request address
        xhr.open(type,url);
        if(type==='get'){
            // send
            xhr.send();
        }else if(type === 'post'){
            //Set request header string / JSON format;
            if(typeof data =="object"){
                xhr.setRequestHeader("content-type","application/json")//JOSN.stringify({a:1,b:2,c:3})
                xhr.send(JSON.stringify(data));
            }else{
                xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")// a=1&b=2&c=3
                xhr.send(data);
            }    
        }
        // monitor
        xhr.onreadystatechange=()=>{
            if(xhr.readyState == 4 && xhr.status == 200){
                alert(xhr.responseText);
            }
        }
    }