Jquery Disclosure Series: ajax Native js Implementation Details of Recommendations

  • 2021-06-28 08:23:53
  • OfStack

Speaking about ajax, we need to know that two objects, XMLHTTPRequest and ActiveXObject, provide full access to the HTTP protocol, including the ability to make POST and HEAD requests as well as ordinary GET requests.The response from the Web server can be returned synchronously or asynchronously, and the content can be returned as text or as an DOM document.XMLHTTPRequest is basically standardized. Compatibility with most browsers, ActiveXObject, is something Microsoft does, so to be compatible with the IE version, we only use its xmlHTTP functionality.

For clarity and clarity of functionality, we divide this ajax code into five parts:

&8226;Object Creation

&8226;onreadystatechange Handle Processing

&8226;Parameter Stitching

&8226;Get Function Implementation

&8226;Post Function Implementation

1. Object creation:

First create the XMLHttp variable that will be used as the XMLHttpRequest object.Set its value to null.

Create objects according to the web standard (Mozilla, Opera, and Safari):XMLHttp=new XMLHttpRequest()

Create objects Microsoft way, available in Internet Explorer 6 and later: XMLHttp=new ActiveXObject ("Msxml2.XMLHTTP")

If errors are caught, try an older method (Internet Explorer 5.5): XMLHttp=new ActiveXObject ("Microsoft.XMLHTTP")


var xhrFactory = function () {
    this.init.apply(this, arguments);
   }
   xhrFactory.prototype = {
    init: function () {
     this.xhr = this.create();
    },
    create: function () {
     var xhr = null;
     try {
      if (window.XMLHttpRequest) {
       xhr = new XMLHttpRequest();
      }
      else if (window.ActiveXObject) {
       xhr = new ActiveXObject("Msxml2.Xmlhttp");
      }
     }
     catch (err) {
      xhr = new ActiveXObject("Microsoft.Xmlhttp");
     }
     return xhr;
    }
}

2.onreadystatechange handle:


readystate: function (timeout,callback) {
     this.xhr.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
       callback(eval("(" + this.responseText + ")"));
      }
      else {
       setTimeout(function () {
        this.xhr.abort();
       }, !timeout ? 15000 : timeout);
      }
      
     }
    }

Here's a look at the readyState and status attributes.

readyState:

1. Create an MLHTTP object
2. Open a connection to the server
3. Send instructions
4. Wait for the result of the request to be processed.

status:

200. The request was successful
400.Request error.
There are many more values, not one here.

The timeout parameter is the request expiration time
callback parameter, the callback handles the returned data and converts it to an object.

3. Parameter splicing


para: function (data) {
     var datastr = "";
     if (data && Object.prototype.toString.call(data) == "[object Object]") {
      for (var i in data) {
       for (var i = 0; i < length; i++) {
        datastr += i + "=" + data[i] + "&";
       }
      }
     }
     return datastr;
    }

Here, the incoming object parameters are concatenated into characters and used to send parameters when an ajax request is made.

4. Get function implementation:


get: function (url, data, callback, async, timeout) {
     this.readystate(timeout, callback);
     var newurl = url;
     var datastr = this.para(data);
     newurl = url + "?" + datastr;
     this.xhr.open("get", newurl, !async ? true : async);
     this.xhr.send(null);
    }

For get requests, the parameters sent are spliced directly on url, not in send, while the post mode parameters are sent in send.

5. Post Function Implementation


post: function (url, data, callback, async, timeout) {
     this.readystate(timeout, callback);
     var newurl = url;
     var datastr = this.para(data);
     this.xhr.open("post", newurl, !async ? true : async);
     this.xhr.setRequestHeader("content-type", "x-www-form-urlencoded");
     this.xhr.send(!datastr ? null : datastr);
    }

post has one more piece of code in it: this.xhr.setRequestHeader ("content-type", "x-www-form-urlencoded");

This code actually means that the entire sent content is encoded as a whole, while get is a single parameter for encoding stitching, which is also the difference between post and get.

Called as follows:


var xhr = new xhrFactory();
   xhr.post("test.ashx", null, function (data) {
    alert(data);
   });

Related articles: