JQuery3.1.1 Source code Interpretation (19) "Ajax"

Source: Internet
Author: User
Tags extend http request json


About Ajax, too many things, I would like to avoid Ajax, avoid to mention, but I think Ajax so much content, not to say it is a pity. 

written before JQuery's Ajax



First, let's take a look at the HTTP request in JS. The HTTP protocol has the request body and the response body, for the request of the party, regardless of which language, I am more concerned about the following aspects: The request configuration parameters including Url,post/get, request the request header, then the request header parameters which function to set, how to tell that the request has been successful , how the response status code and response data are obtained, and so on. 

XMLHttpRequest Object



Every day shouting to write the native JS request, then came, is this function XMLHttpRequest, it is a set of JavaScript, VbScript, JScript and other scripting languages through the HTTP protocol to send or receive XML and other data of the set of APIs, The evil low version IE has a compatible activexobject.



It has two versions, the first version has few features, and in the near future there is a more complete version 2.0, more functional. If you are interested, you can come here and take a look at XMLHttpRequest. If you have a good grasp of the HTTP protocol, you can also look at the following content.

  implement a simple Ajax request



If you run into an interviewer and ask you to write a native Ajax request, the following may be very helpful:


Myajax var Myajax = (function () {var defaultoption = {url:false, type: ' GET ', Data:null, success: False, Complete:false} var ajax = function (options) {for (var i in defaultoption) {options[i] = option S[i] | |
    Defaultoption[i];
    }//HTTP object var xhr = new XMLHttpRequest ();
    var url = options.url;
    Xhr.open (options.type, URL);
      Monitor Xhr.onreadystatechange = function () {if (xhr.readystate = = 4) {var result, status = Xhr.status;
        } if (Status >= && Status < | | status = = 304) {result = Xhr.responsetext; if (window.
        JSON) {result = Json.parse (result);
        }else{result = eval (' (' + result + ') '); } ajaxsuccess (Result)}}//Post if (options.type.toLowerCase () = = = ' Post ') {Xhr.setreques
    Theader (' Content-type ', ' application/x-www-form-urlencode ');

    } xhr.send (Options.data); function Ajaxsuccess (Data) {var status = ' success ';
      Options.success && options.success (data, options, status, XHR);
    Options.complete && options.complete (status);
}}//Closure returns the return AJAX; })()


The test is below:


var success = function (data) {
  console.log (data[' blog ')
}
var complete = function (status) {
  if (status = = ' Success ') {
    console.log (' success ')
  }else{
    console.log (' failed ')
  }
}
myajax ({
  URL: ' Https://api.github.com/users/songjinzhong ',
  success:success,
  complete:complete
});


You can get a simple usage of XMLHttpRequest: Create an HTTP Request object with new XMLHttpRequest (), the function of the open function is to set the URL and type to open, establish a connection, but at this point the request is not sent; Setrequest Header to set the request header information; The Send function sends a data request like a server; onreadystatechange is a listener function that executes when readyState changes, 1-2-3-4,4 indicates a successful return. Xhr.responsetext is the response data returned, it is clear that here is the JSON format, actually to be judged by the response header, this step is omitted here, getAllResponseHeaders can get all the response header; Success function and complete The location and order of function execution issues. 

features of JQuery Ajax



The above example should be able to have a general understanding of the HTTP request of JS, and the processing of jQuery is more complex, but also related to functions similar to the above, and for callback and deferred,jquery itself support:


var deferred = jquery.deferred (),
  completedeferred = Jquery.callbacks ("Once Memory");


So, JQuery is a self-sufficient library, not too much, ahead of the Sizzle, the entire source is filled with extend functions, and so on. 

Jquery.ajaxsetup



Ajaxsetup is a function that is executed early in the AJAX function, which is mainly used to calibrate parameters;


Jquery.extend ({
  ajaxsetup:function (target, settings) {
    return settings?

      Double-layered ajaxextend function
      ajaxextend (ajaxextend (target, jquery.ajaxsettings), settings):

      //Extending Ajaxsettings
      ajaxextend (jquery.ajaxsettings, target);
  },
} );


Ajaxsettings is an object, specifically what to do with, see To know:


Jquery.ajaxsettings = {url:location.href, type: "GET", IsLocal:rlocalProtocol.test (Location.protocol), global : True, Processdata:true, Async:true, ContentType: "application/x-www-form-urlencoded;  Charset=utf-8 ", accepts: {" * ": alltypes, Text:" Text/plain ", HTML:" text/html ", xml:" Application/xml,
    Text/xml ", JSON:" Application/json, Text/javascript "}, Contents: {xml:/\bxml\b/, HTML:/\bhtml/, 

  JSON:/\bjson\b/}, Responsefields: {xml: "Responsexml", Text: "ResponseText", JSON: "Responsejson"},  Data Converters//Keys separate source (or catchall "*") and destination types with a single space converters:  {//Convert anything to text ' * text ': String,//Text to HTML (true = no transformation) "Text HTML": True,//Evaluate text as a JSON expression "text json": json.parse,//Parse text as XML "text XML": J Query.parsexml},//For options that shouldn 't be deep extended://Can add your own custom options here if//And when you create one that shouldn ' t is//d Eep extended (see Ajaxextend) flatoptions: {url:true, context:true}}


Ajaxsettings turned out to be an enhanced version of the options.



Ajaxextend is used to standardize the AJAX function parameters to see which parameters are not assigned, so that it is equal to the default value, because Ajaxextend is double-layered, specifically to debug to be more clear.


function ajaxextend (target, src) {
  var key, deep,
    flatoptions = JQuery.ajaxSettings.flatOptions | | {};

  For (key in SRC) {
    if (src[key]!== undefined) {
      (flatoptions[key]? Target: (Deep | | (deep = {})) ) [Key] = src[key];
    }
  }
  if (deep) {
    jquery.extend (true, target, deep);
  }

  return target;
}
AJAX.JQXHR


In Ajax there is a very important object, JQXHR, although it is a short, but by the abbreviation can also roughly guess it is jquery-xmlhttprequest.


JQXHR = {readystate:0,///0-4//familiar with the response header should not be unfamiliar to this, the response header data stored according to key value Getresponseheader:function (key) {
    var match;
        if (completed) {if (!responseheaders) {responseheaders = {}; while (match =/^ (. *): [\t]* ([^\r\n]*) $/mg.exec (responseheadersstring))) {responseheaders[match[1].t
        Olowercase ()] = match[2];
    }} match = Responseheaders[key.tolowercase ()]; } return match = = null?
  Null:match;
  },//Raw string getallresponseheaders:function () {return completed? Responseheadersstring:null; },//Manually set the request header Setrequestheader:function (name, value) {if (completed = = null) {name = REQUESTHEADERSN ames[name.tolowercase ()] = requestheadersnames[name.tolowercase ()] | |
      Name
    requestheaders[name] = value;
  } return this;
},//Overrides response Content-type Header overridemimetype:function (type) {if (completed = = null) {      S.mimetype = type;
  } return this;
    },//Status-dependent callbacks Statuscode:function (map) {var code; if (map) {if (completed) {//Execute the appropriate callbacks Jqxhr.always (map[Jqxhr.statu
      S]); } else {//Lazy-add the new callbacks in a-on-the-preserves old ones for (code in map) {s
        tatuscode[code] = [statuscode[code], map[code]];
  }}} return this;
    },//Cancel the request Abort:function (statustext) {var finaltext = StatusText | | strabort;
    if (transport) {transport.abort (finaltext);
    } done (0, finaltext);
  return this; }
};


JQXHR has completely replaced the XHR object, and the functions have been expanded. 

Ajaxtransport



So where exactly is XMLHttpRequest this function?



There are two properties in JQuery, namely Ajaxprefilter and Ajaxtransport, which are constructed by the Addtoprefiltersortransports function. The main ajaxtransport function:


Jquery.ajaxtransport (options) {var callback, Errorcallback; Cross domain only allowed if supported through XMLHttpRequest if (support.cors | | xhrsupported &&!OPTIONS.C Rossdomain) {return {send:function (headers, complete) {var i, xhr = OPTIONS.XHR ();//XH
          R () = XMLHttpRequest () xhr.open (Options.type, Options.url, Options.async,

        Options.username, Options.password);
            Apply custom Fields if provided if (Options.xhrfields) {to (I in Options.xhrfields) {
          xhr[i] = options.xhrfields[i];
          }}//Override MIME type if needed if (Options.mimetype && xhr.overridemimetype) {
        Xhr.overridemimetype (Options.mimetype);
        }//X-requested-with header//For Cross-domain requests, seeing as conditions for a preflight is akin to a jigSaw puzzle, we simply never set it to be sure.  (It can always is set on a per-request basis or even using ajaxsetup)//For Same-domain requests, won ' t change
        Header if already provided. if (!options.crossdomain &&!headers["X-requested-with"]) {headers["x-requested-with"] = "XMLHttp
        Request ";
        }//Set headers for (i in headers) {Xhr.setrequestheader (I, headers[i]);
              }//Callback Callback = function (type) {return function () {if (Callback) { callback = Errorcallback = Xhr.onload = Xhr.onerror = Xhr.onabort = Xhr.onreadystatechange =

              Null
              if (type = = = "Abort") {Xhr.abort (); } else if (type = = = "Error") {//Support:ie <=9 only//on a manual native Abort, IE9 throws//errors on the Any property access that's not reAdystate if (typeof xhr.status!== "number") {Complete (0, "error");
                    } else {complete (//file:protocol-yields status 0; see #8605, #14207
                Xhr.status, Xhr.statustext);
                  }} else {complete (xhrsuccessstatus[Xhr.status] | | xhr.status, Xhr.statustext,//Support:ie <=9 only//IE9 have no XHR2 but throws O n Binary (trac-11426)//For XHR2 Non-text, let the caller handle it (gh-2498) (XHR.R Esponsetype | |
                  "Text")!== "text" | |
                    typeof Xhr.responsetext!== "string"?
                {Binary:xhr.response}: {Text:xhr.responseText}, Xhr.getallresponseheaders ()
              );
   }
            }       };

        };
        Listen to Events Xhr.onload = callback ();

        Errorcallback = Xhr.onerror = Callback ("error");  Support:ie 9 only//use onreadystatechange to replace onabort//To handle uncaught aborts if (Xhr.onabort!== undefined)
        {xhr.onabort = Errorcallback;
            } else {xhr.onreadystatechange = function () {//Check readyState before timeout as it changes if (xhr.readystate = = = 4) {//Allow onerror to be called First,//and that would Not handle a native abort//Also, save Errorcallback to a variable//as Xhr.onerror cannot b e Accessed Window.settimeout (function () {if (callback) {Errorcallback
                ();
            }
              } );
        }
          };

  }//Create the abort callback callback = Callback ("Abort");      try {//Do send the request (this could raise an exception) Xhr.send (Options.hascontent &AMP;&A mp Options.data | |
        NULL); } catch (E) {//#14683: Only rethrow if the hasn ' t been notified as an error yet if (callback)
          {throw e;
        }}, Abort:function () {if (callback) {callback ();
  }
      }
    }; }
} );


The return value of the Ajaxtransport function has two, where send is the sending function, step by step, sent down, without much explanation.



In addition, Ajax provides a number of callback functions for JQuery objects in the AJAX process:


Jquery.each ([
  "Ajaxstart",
  "Ajaxstop",
  "Ajaxcomplete",
  "Ajaxerror",
  "ajaxsuccess",
  " Ajaxsend "
], function (i, type) {
  jquery.fn[type] = function (fn) {
    return This.on (Type, fn);
  };
} );

JQuery.event.trigger ("Ajaxstart");
...
Globaleventcontext.trigger ("Ajaxsend", [JQXHR, S]);
...
Globaleventcontext.trigger (issuccess? "Ajaxsuccess": "Ajaxerror", [Jqxhr, S, issuccess? Success:error]);
...
Globaleventcontext.trigger ("Ajaxcomplete", [JQXHR, S]);
...
JQuery.event.trigger ("Ajaxstop");


There are too many Ajax things, at least 1000 lines of code. 

Summary



About Ajax, do not want to go into the deep research, the recent summer internship school recruit has begun to start, temporarily put a bar, and later have time to pits it. 


Reference



jquery Source Analysis Series: The overall structure of Ajax



jquery Source Analysis Series (PNS): Ajax Summary



Touch Jquery:ajax Asynchronous explanation


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.