Ajax series of in-depth understanding of the first chapter (XHR object)

  In 1999, Microsoft released IE5, for the first time to introduce a new feature: Allow javascript to initiate hffp request to the server. This feature was not the way to attract attention, knowing published in 2004 Gmail and Google Map released, it attracted wide attention. In February 2005, ajax first official presentation of the word, refers to the development of a set of functionality around this practice, since then, ajax called script initiated synonymous http communication, W3C also released its 2006 international standards.

Overview:

  Ajax is asynchronous javasricot and XM; L shorthand, Chinese translation is asynchronous javascript and Xml, this technology can request additional data to the server without uninstalling the page, bring back a better user experience, although the name is included in XML, ajax but not to communicate with the data format.

  Ajax consists of the following steps:

    1. Create Ajax object

    2, an HTTP request

    3, to accept the return of server data

    4, the data update a web page

    After then, summed up in one sentence, Ajax sent out through the XMLHttpRequest object native HTTP request to obtain the data server, processing is performed

create:

  Ajax core technology is the XMLHttpRequest object (referred to as XHR), which is received by Microsoft introduced a feature first, then all other browser vendors offer the same realization, XHR to send a request to the server response and resolution services provided by the server smooth the interface can get more information from the server asynchronously, meaning that the user stand-alone post, than you can refresh the page to obtain new data.

  IE5 is the first to introduce XHR object browser, in IE5, XHR object is achieved by an Active MSXML library objects ,, and IE7 + and other standard browsers support XHR object native

  Create a XHR object, also known instance of an XHR object because XMLHTTPRequest () is a constructor, the following is to create a XHR object is compatible with the wording:

  

var xhr:
if(window.XMLHttpRequest){
    xhr = XMLHttpRequest();  
}else{
    xhr = new ActiveXobject("Microsoft.XMLHTTP");
}

  note:

    If you want to build N different requests, you must use a different phone XHR object, of course, you can reuse the XHR object to exist, but that any request to terminate pending before

send request:

  open()

    In use XHR object, a first method is to call Open (), as shown below, which accepts three parameters

xhr.open('get','example.php', false)

    1, the first argument open () method is used to specify a transmission request, the character string, case-insensitive, but usually uppercase, "GET" and "POST" wide support

    2, "GET" request is routine, it uses the URL when fully specified resources and, when the request without any side effects, and in the case where the service books is responsive cacheable

    3, "POST" for party send HTML form, which contains additional data in the request body, and often the data stored in the database on the server, the same repeating POST URL request response from the server may be obtained from a different, without using this method should be cached request

    4, in addition to the "GET" and "POST", the parameter can be "HEAD", "OPTIONS", "PUT". And because of security risks, "CONNECT", "TRACE", "TRACK" are banned

    

    5, the second parameter open () method is a URL, which executes code relative to the current page, and the URL can send requests to the same port and protocol with the use of a domain, if the URL of the page start request any differences will lead to a security error

    6, the third argument open () method is a Boolean value indicating whether the request is sent asynchronously, if you do not fill, the default is True, represents the asynchronous transmit

    7, if the request to close a password-protected URL. The authentication for the user name and password as the fourth and fifth transmission parameter to the open () method

  send()

    After the send () method takes one parameter, both the data to be transmitted from the request body, call send () method, the request is assigned to the server

    If the "GET" method, send () method without parameters, or parameter is null, if the post method parameters send () method for data to be transmitted

      

xhr.open('GET', 'example.php', false);
xhr.send(null);

 

Receiving a response:

    A complete response by the HTTP status code and the response in response to the first set of themes that, after receiving the response, which can be used by the XHR object properties and methods, there are the following four properties:

  

responseText: body is returned as a response text (text) 
the responseXML: If the response of the same type is "text / XML" or "file application / XML", this property holds in the XML response data, DOM document (document in the form of ) 
status: the HTTP status code (in digital form) 
the statusText: the HTTP status descriptions (text)

  After receiving the response, the first step is to check the status attribute to determine a response has been successfully returned. In general, HTTP status code 200 may be the most successful logo. In this case, the content attribute responseText ready, and in the case of the correct content type, the responseXML can also access, and in addition, the status code 304 indicating a request for the resource has not been modified, may be used directly cached version of the browser; of course, also means that the response is valid

  No matter what content type is the contents of the response body will be saved to the responseText property, and for XML data, the value of the property will be null responseXML

if(xhr.status >= 200 && xhr.status == 304){
    alert(xhr.responseTEXT);
}else{
    alert("request was unsuccessful:"+ xhr.status);    
}

 

Synchronize:

  If the received response is synchronized, the third parameter needs to be open () method is set to false, then the send () method will be blocked until the request is completed, once the send () method returns, the object is only necessary status and traitor XHR responseText property to

  Synchronous requests are attractive, but they should be avoided, the client javascriot is single-threaded, when the send () method blocks, it usually will cause the entire browser UI freeze, if the server connection is slow to respond, then the user's browser will freeze

<Button ID = " BTN " > Get Information </ Button> 
<div ID = " Result " > </ div> 
<Script> 
btn.onclick = function () {
     // create objects xhr 
    var xhr;
     IF (window.XMLHttpRequest ) { 
        XHR = new new the XMLHttpRequest (); 
    } the else { 
        XHR = new new the ActiveXObject ( ' Microsoft.XMLHTTP ' ); 
    } 
    // send request 
    xhr.open ( ' GET ' , '/uploads/rs/26/ddzmgynp/message.xml ' , to false ); 
    xhr.send (); 
    // synchronization accept response 
    IF (xhr.readyState == . 4 ) {
         IF (xhr.status == 200 is ) {
             // practice 
            result.innerHTML + = xhr.responseText; 
        } 
    } 
}
 </ Script>   

 

asynchronous:

  If the request requires asynchronous reception, which requires the detection readyStatus XHR object attribute, the attribute indicates the currently active phase request / response process, the desirable property values ​​are as follows:

  

0 (UNSEND): uninitialized, Open not been called () method
 . 1 (the OPENED): start, has been called open () method, but yet send () method
 2 (HEADERS_RECEIVED): sending, it has been called Dend () method, and receives the header information
 . 3 (LOADING): receiving, in response to the body part has received the information
 . 4 (the DONE): completed, all the response data has been received, the client may have two hundred seventy-five use

  In theory, as long as the property value has a value readyStatus program another value, it triggers a readyStatusChange event. You can use this time after each detected value readyStatus state change. Usually, we stage readyStatus the value of 4 willing to go, it should mean that the data is ready yo

  Note:
    need to ensure browser compatibility at a specified time before onreadyStatuschange call open () handler, or they will not receive readyStatus property to 0 and 1 case

xhr.onreadystatechange = function(){
    if(xhr.readyState === 4){
        if(xhr.status == 200){
            alert(xhr.responseText);
        }
    }
}

 

<Button ID = " BTN " > Get Information </ Button> 
<div ID = " Result " > </ div> 
<Script> 
btn.onclick = function () {
     // create objects xhr 
    var xhr;
     IF (window.XMLHttpRequest ) { 
        XHR = new new the XMLHttpRequest (); 
    } the else { 
        XHR = new new the ActiveXObject ( ' Microsoft.XMLHTTP ' ); 
    } 
    // asynchronous accept response 
    xhr.onreadystatechange = function () {
         IF(== xhr.readyState . 4 ) {
             IF (xhr.status == 200 is ) {
                 // practice 
                result.innerHTML + = xhr.responseText; 
            } 
        } 
    } 
    // send request 
    xhr.open ( ' GET ' , ' Message. XML ' , to true ); 
    xhr.send (); 
}
 </ Script>    

 

time out:

  After the timeout attribute XHR object is equal to an integer representing the number of milliseconds, if the request is still not getting the results, it will automatically terminate, the default attribute equals 0, indicating no time limit

  If the request times out, the event will trigger ontimeout

  note:

     IE8 browser does not support this property

  

xhr.open("post", 'test.php', true)
xhr.ontimeout = function(){
    console.log("The request timeed out !!! ")
}

xhr.timeout = 1000,
xhr.send();

optimization:

   When receiving data using Ajax, due to the size of the network and data, while not immediately be displayed on the page out, so the better approach is in the process of receiving data, it shows a small picture of a similar loading and disabled button, when the data is received completely hidden to the picture, and turn on the button:

 

 

<button id="btn">获取信息</button>
<img id="img" height="16" style="display:none" src="data:image/gif;base64,R0lGODlhIAAgALMAAP /// 7Ozs / v7 + 9bW1uHh4fLy8rq6uoGBgTQ0NAEBARsbG8TExJeXl / 39 / VRUVAAAACH / C05FVFNDQVBFMi4wAwEAAAAh + QQFBQAAACwAAAAAIAAgAAAE5xDISSlLrOrNp0pKNRCdFhxVolJLEJQUoSgOpSYT4RowNSsvyW1icA16k8MMMRkCBjskBTFDAZyuAEkqCfxIQ2hgQRFvAQEEIjNxVDW6XNE4YagRjuBCwe60smQUDnd4Rz1ZAQZnFAGDd0hihh12CEE9kjAEVlycXIg7BAsMB6SlnJ87paqbSKiKoqusnbMdmDC2tXQlkUhziYtyWTxIfy6BE8WJt5YEvpJivxNaGmLHT0VnOgGYf0dZXS7APdpB309RnHOG5gDqXGLDaC457D1zZ / V / nmOM82XiHQjYKhKP1oZmADdEAAAh + QQFBQAAACwAAAAAGAAXAAAEchDISasKNeuJFKoHs4mUYlJIkmjIV54Soypsa0wmLSnqoTEtBw52mG0AjhYpBxioEqRNy8V0qFzNw + GGwlJki4lBqx1IBgjMkRIghwjrzcDti2 / Gh7D9qN774wQGAYOEfwCChIV / gYmDho + QkZKTR3p7EQAh + QQFBQAAACwBAAAAHQAOAAAEchDISWdANesNHHJZwE2DUSEo5SjKKB2HOKGYFLD1CB / DnEoIlkti2PlyuKGEATMBaAACSyGbEDYD4zN1YIEmh0SCQQgY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C6H6CVAJaCcT0CUBTgaTg5nTCu9GKiDEMPJg5YBBOpwlnVzLwtqyKnZagZWahoMB2M3GgsHSRsRACH5BAUFAAAALAEACAARABgAAARcMKR0gL34npkUyyCAcAmyhBijkGi2UW02VHFt33iu7yiDIDaD4/erEYGDlu/nuBAOJ9Dvc2EcDgFAYIuaXS3bbOh6MIC5IAP5Eh5fk2exC4tpgwZyiyFgvhEMBBEAIfkEBQUAAAAsAAACAA4AHQAABHMQyAnYoViSlFDGXBJ808Ep5KRwV8qEg+pRCOeoioKMwJK0Ekcu54h9AoghKgXIMZgAApQZcCCu2Ax2O6NUud2pmJcyHA4L0uDM/ljYDCnGfGakJQE5YH0wUBYBAUYfBIFkHwaBgxkDgX5lgXpHAXcpBIsRADs=ud2pmJcyHA4L0uDM/ljYDCnGfGakJQE5YH0wUBYBAUYfBIFkHwaBgxkDgX5lgXpHAXcpBIsRADs=ud2pmJcyHA4L0uDM/ljYDCnGfGakJQE5YH0wUBYBAUYfBIFkHwaBgxkDgX5lgXpHAXcpBIsRADs=" alt="loading">
<div id="result"></div>
<script>var add = (function(){
    var counter = 0;
    return function(){
        return ++counter;
    }
})();
btn.onclick = function(){
    img.style.display = 'inline-block';
    btn.setAttribute('disabled','');
    varcreate an object xhr//

     xhr;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else{
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    //异步接受响应
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if(xhr.status == 200){
              img.style.display = 'none';
              btn.removeAttribute('disabled');
              var data = JSON.parse(xhr.responseText);
              var sum = add() - 1;
              if(sum < data.length){
                result.innerHTML += data[sum];    
              }
            }
        }
    }
    //发送请求
    xhr.open('get','data.php',true);
    xhr.send();
}
</script>      

  Ajax front-end content itself is not difficult, however, because the Ajax and involve a number of back-end network only, so that is not very easy to learn.

 

 

This article is excerpted: https: //www.cnblogs.com/xiaohuochai/p/6036475.html

  

 

 

   

 

 

 

 

  

 

  

 

Guess you like

Origin www.cnblogs.com/jcjc/p/11573946.html