ajax study notes

1. What is

  AJAX (Asynchronous JavaScript and xml) is an approach that uses existing standards.

2. What's the use

  Realize the exchange of data with the background without refreshing the entire page, and realize the partial update of the page.

3. How to use

  AJAX initiates a request to the server through the XMLHttpRequest object, obtains data from the server, and then updates the data to the page through JavaScript.

 function AjaxRequest(){
         var xxhr;
         // 1. Create xmlHttpRequest object 
        if (window.XMLHttpRequest) { // For current mainstream browsers 
            xhr= new XMLHttpRequest();
        }
        else { // For older browsers (IE6, IE5) 
            xhr= new ActiveXObject("Microsoft.XMLHTTP" );
        }
        // 2. Create an http request and specify the method, URL, and whether it is asynchronous (the data is followed by the url, separated by ?) 
        xhr.open('get','server.php', true );
         // The post request needs to set the content-type of the request header 
        // xhr.setRequestHeader('content-type','application/x-www-form-urlencoded'); 
        // 3. Send http request, get request can be empty , the post request puts the data into send and sends 
        xhr.send();
         // 4. Set the listener function, and execute it every time readyState changes 
        // readyState stores the state of XMLHttpRequest. Varies from 0 to 4. 
        //   0: The request is not initialized 
        //   1: The server connection has been established 
        //   2: The request has been received 
        //   3: The request is being processed 
        //   4: The request has been completed, 
        //       status code status (common): 200-OK, 404-NOT FOUND
        xhr.onreadystatechange= function () {
             // When readyState is equal to 4 and the state is 200, it means the response is ready 
            if (xhr.readyState == 4&&xhr.status==200 ) {
                 var result= xhr.responseText;
                alert(result);
            }
        }
        // If the async of open is set to false, it means synchronization, you don't need to set the listener function 
        // var result=xhr.responseText; 
    }
view code

 

     

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325387926&siteId=291194637