Ajax objects from 0 to 1 learning Web front-end JavaScript (i)

Source: Internet
Author: User



Now the most popular way to get back-end (browser-from-server) data is through Ajax. Come to learn this knowledge in detail today. If you use Ajax to access the latter segment of the data, browser and browser-side JS do that work? I made a diagram, please look at:


1. The way of the native JS Ajax request


By the above figure we have a general idea of the process of Ajax accessing back-end data. The most important thing is the process of detecting the browser and creatingXMLHttpRequestthe object:
The code is as follows:


/*
  Determine whether XMLHttpRequest is supported
  */
Function createXHR() {
     If (typeof XMLHttpRequest != "undefined") {
         Return new XMLHttpRequest();
     }
     Else if (typeof ActiveXobject != "undefined") {
         If (typeof arguments.callee.activeXString != ‘string‘) {
             Var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"], i, len;
             For (i = 0, len = versions.length; i < len; i++) {
                 Try {
                     New ActiveXObject(versions[i]);
                     arguments.callee.activeXString = versions[i];
                     Break;
                 }
                 Catch (ex) {
                     Console.log(ex);
                 }
             }
         }
         Return new ActiveXObject(arguments.callee.activeXString());
     }
     Else {
         Throw new Error(‘no XHR‘)
     }
} 


This is based on whether the browser supportsXMLHttpRequestobjects to determine whether it is IE or non-ie, and then creates the object for the response.



When the Xhr object isopen()not sent an HTTP request to the Web server at this time,send()the XHR object sends the request to the Web server instead.


xhr.send(‘‘);


There is a very important place here, which issendthe parameternull.


send()method receives a parameter that requires data to be sent as the request principal. If you do not need to send data as the request principal, you must pass in NULL, because this parameter is required for some browsers.


When the browser receives a response from the Web server, it starts populating the properties of the Xhr object, mainly as follows:


    • responseTextThe text to be returned as the body of the response
    • responseXMLIf the content type of the response is or if thetext/xmlapplication/xmlproperty will contain aXMLDOMdocument that responds to data
    • statusHTTP status of the response
    • statusTextDescription of the HTTP status

      TypicallyXHR.status, the attribute value is200the flag that represents success. You can getresponseTextthe value at this timeresponseXML. WhenXHR.status==304(the response is valid ), the description file has not been modified, you can directly use the browser cached version.


The code for the detection is as follows:


 
if (xhr.status >= 200 && xhr.status <= 300 || xhr.status == 304) {
                console.log(xhr.responseText);
            }
            else {
                console.log(xhr.responseText);
            }

Do not rely on itresponseTextbecause the value obtained by this property is unreliable when cross-browser processing.


The above code does not have any problems in synchronizing the request validation and retrieving the data for the rebate. But when we send an asynchronous request, there really is a problem because we don't know when the server is goingResponseback. So what do we do?



In fact, when Ajax sends a request to the Web server, there is a readystate property to detect the Xhr object请求/响应过程的当前活动阶段, and the list of values is as follows:


    • 0Not initialized. Method not yet calledopen()
    • 1Start. Method has been calledopen(), but method has not been calledsend()
    • 2Send. The method has been calledsend(). However, the response has not been received yet.
    • 3Receive. Part of the response data has been received.
    • 4Complete. All the response data has been received and is already available to the client.

      WheneverXHR.readyStatea property value changes, an event is triggeredonreadystatechange. Usually we are onlyXHR.readyState==4interested in the time (when the data is all ready).

You mustopen()specify anonreadystatechangeevent handler before calling to guarantee the compatibility of your browser.


The instance code is as follows:


 
 
var xhr = new createXHR();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status >= 200 && xhr.status <= 300 || xhr.status == 304) {
                console.log(xhr.responseText);
                //console.log(xhr.)
                //document.createElement()
                creatNode(‘script‘);
                creatNode(‘img‘);
            }
            else {
                console.log(xhr.responseText);
            }
        }
    }
    xhr.open(‘GET‘, ‘test.js‘, true);
    xhr.send(‘‘);
2.jQuery ways to send Ajax


Referring to jquery's documentation, using jquery to send AJAX requests is much simpler than native JS. The following code:


2.1GET mode
$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script"
});
2.2POST mode
$.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
});


Here is also a simple example, if you want to learn more about the use of Ajax in jquery. You can refer to the official jquery documentation.
Chinese documents (Click to go)
English documents (click to go)



Ajax objects from 0 to 1 learning Web front-end JavaScript (i)


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.