Ajax native


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
                //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
                        //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
            // send
        }else if(type === 'post'){
            //Set request header string / JSON format;
            if(typeof data =="object"){
                xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")// a=1&b=2&c=3
        // monitor
            if(xhr.readyState == 4 && xhr.status == 200){

Recommended Today

JQuery’s promise

Promise is an asynchronous programming specification, transliteration to understand –“Prometheus” Prometheus is a hero in Greek mythology, whose name means “prophet”. Promise was originally named “futures”. It can be seen that promise does not mean literally “oath”, “promise”, etc., but “prophet” and “future”. Promise is to solve the most headache in asynchronous programmingCallback nesting region […]