Brief introduction to jQuery asynchronous object (XMLHttpRequest)

  • 2020-03-30 04:18:27
  • OfStack

Let's first look at the quintuple of asynchronous objects

This is the post request,


 //1.00 create an asynchronous object
            var xhr = new XMLHttpRequest();
            //2.0
            xhr.open("post", url,params, true);
            //3.0 passes the parameter
using the Formdata attribute             xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            //4.0 setting callback function
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    alert(xhr.responseText);
                }
            }
            //5.0 passes the parameter
            xhr.send(params);

Encapsulate an asynchronous object with a get request

In a get request

  XHR. SetRequestHeader (" the if-modified-since ", "0"); To clear the cache

Post requests


 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

It's for transmission
In < The from method = "post" type = "" >
< From> Type in the code can be coded in three ways, including application/x-www-form-urlencoded
 


var ajaxHelp = {
    CreatXHR: function () {
        //Create an asynchronous object
        var xhr = new XMLHttpRequest();
        return xhr;
    },
    //Ajax get request
    AjaxGet: function (url, callBack) {
        this.AJaxCommon("get", url, null, callBack);
    },
    //Post request for ajax
    AjaxPost: function (url, params, callBack) {
        this.AJaxCommon("post", url, params, callBack);
    },
    AJaxCommon: function (method, url, params, callBack) {
        //1.0
        var xhr = this.CreatXHR();
        //2.0
        xhr.open(method, url, true);
        //3.0
        if (method == "get") {
            xhr.setRequestHeader("If-Modified-Since", "0");
        } else {
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        }
        //4.0
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var datas = JSON.parse(xhr.responseText);
                //Execute the callback function
                callBack(datas);
            }
        }
        //5.0
        xhr.send(params);
    }
};

Ps: in JQuery there is $. Ajax ; And $. Get /     $. Post  Of the asynchronous request method. The old encapsulation was not used. The forehead. Good pull. In fact, that's what they wrote at the bottom. JQuery is all about compatibility between browsers

The above is my understanding of jQuery asynchronous object (XMLHttpRequest), if there is any omission, please contact me, add on.


Related articles: