ajax topic

Introduction to ajax:

  ajax = Asynchronous JavaScript and XML.
  Ajax is a technology that can update parts of a web page without reloading the entire web page. We know that traditional web pages (without using ajax) have to reload the entire web page if the content needs to be updated. The advent of Ajax makes it possible to update the web asynchronously, which means that parts of a web page can be updated without reloading the entire web page.

working principle:

  The core of ajax technology or responsible for ajax to make synchronous or asynchronous server requests is the XMLHttpRequest object. When using ajax technology, it is actually operating XMLHttpRequest for corresponding business.

Regarding the XMLHttpRequest object:

Create an XMLHttpRequest object:

  All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects.

  With a simple line of JavaScript code, we can create an XMLHttpRequest object.

The syntax for creating an XMLHttpRequest object:

xml =new XMLHttpRequest();

Properties and methods of the XMLHttpRequest object

Attributes

  readyState property

  When an XMLHttpRequest object sends an HTTP request to the server it goes through several states: it waits until the request is processed; then, it receives a response. In this way, the script correctly responds to various states - the XMLHttpRequest object exposes a readyState property that describes the current state of the object, as shown in Table 1.

  Table 1. List of ReadyState property values ​​for XMLHttpRequest objects.

ReadyState value describe
0
Describes an "uninitialized" state; at this point, an XMLHttpRequest object has been created, but not yet initialized.
1
Describes a "send" state; at this point, the code has called the XMLHttpRequest open() method and XMLHttpRequest is ready to send a request to the server.
2
Describes a "send" state; at this point, a request has been sent to the server via the send() method, but a response has not yet been received.
3
Describes a "receiving" state; at this point, the HTTP response header information has been received, but the message body has not been fully received.
4
Describes a "loaded" state; at this point, the response has been fully received.

  responseText property

  The responseText property contains the text content of the HTTP response received by the client. When the readyState value is 0, 1, or 2, responseText contains an empty string. When the readyState value is 3 (receiving), the response contains information about the client's unfinished response. When readyState is 4 (loaded), the responseText contains the complete response information.

  responseXML attribute

  This responseXML attribute is used to describe the XML response when a complete HTTP response is received (readyState is 4); at this time, the Content-Type header specifies that the MIME (media) type is text/xml, application/xml or +xml end. If the Content-Type header does not contain one of these media types, the value of responseXML is null. Whenever the readyState value is not 4, the value of the responseXML is also null.

  In fact, the value of the responseXML attribute is an object of type document interface, which is used to describe the document being parsed. If the document cannot be parsed (eg, if the document is not well-formed or does not support the document's corresponding character encoding), the value of responseXML will be null.

  status attribute

  The status attribute describes the HTTP status code and is of type short. Also, this status property is only available when the readyState value is 3 (receiving) or 4 (loaded). Attempting to access the value of status while the value of readyState is less than 3 will throw an exception.

  statusText property

  The statusText property describes the HTTP status code text; and is only available if the readyState value is 3 or 4. Attempting to access the statusText property while readyState is any other value will throw an exception.

method (used to initialize and handle HTTP requests)

  abort() method

  You can use the abort() method to suspend the HTTP request associated with an XMLHttpRequest object, thereby resetting the object to its uninitialized state.

  open() method

  You need to call open(DOMString method, DOMString uri, boolean async, DOMString username, DOMString password) method to initialize an XMLHttpRequest object. Among them, the method parameter is mandatory - used to specify the HTTP method you want to use to send the request (GET, POST, PUT, DELETE or HEAD). To send data to the server, the POST method should be used; to retrieve data from the server, the GET method should be used. In addition, the uri parameter is used to specify the corresponding URI of the server to which the XMLHttpRequest object sends the request. With the help of the window.document.baseURI property, the uri is resolved as an absolute URI - in other words, you can use a relative URI - it will be resolved in the same way as the browser resolves a relative URI. The async parameter specifies whether the request is asynchronous - the default is true. In order to send a synchronous request, this parameter needs to be set to false. For servers requiring authentication, you can provide optional username and password parameters. After calling the open() method, the XMLHttpRequest object sets its readyState property to 1 (open) and resets the responseText, responseXML, status, and statusText properties to their initial values. Also, it resets the request headers. Note that if you call the open() method and the readyState is 4, the XMLHttpRequest object will reset these values.

  send() method

  After preparing a request by calling the open() method, you need to send the request to the server. You can call the send() method only when the readyState value is 1; otherwise, the XMLHttpRequest object will raise an exception. The request is sent to the server using the parameters provided to the open() method. When the async parameter is true, the send() method returns immediately, allowing other client-side script processing to continue. After calling the send() method, the XMLHttpRequest object sets the value of readyState to 2 (send). When the server responds, the XMLHttpRequest object will set readyState to 3 (receiving), if any, before receiving the body. When the request finishes loading, it sets readyState to 4 (loaded). For a request of type HEAD, it will set the readyState value to 4 immediately after setting it to 3.

  The send() method takes an optional parameter - this parameter can contain variable types of data. Typically, you use it and send data to the server via the POST method. Additionally, you can explicitly call the send() method with a null argument, just as you would call it with no arguments. For most other data types, the Content-Type header should be set using the setRequestHeader() method (see below) before calling the send() method. If the data parameter in the send(data) method is of type DOMString, then the data will be encoded as UTF-8. If the data is of type Document, the data will be serialized using the encoding specified by data.xmlEncoding.

  setRequestHeader() method

  The setRequestHeader(DOMString header, DOMString value) method is used to set the header information of the request. When the readyState value is 1, you can call this method after calling the open() method; otherwise, you will get an exception.

  getResponseHeader() method

  The getResponseHeader(DOMString header, value) method is used to retrieve the header value of the response. This method can only be called if the readyState value is 3 or 4 (in other words, after the response headers are available); otherwise, the method returns an empty string.

  getAllResponseHeaders() method

  The getAllResponseHeaders() method returns all response headers as a string (each header occupies a separate line). If the value of readyState is not 3 or 4, the method returns null.

 

Usage of AJAX

  

function to_store(){
    $.ajax({
                        type: "post",
                        url : "${basePath}user/updateDetails",
                        data: "field="+field+"&content="+content+"&username="+username,
                        success: function(i){
                            if (i==1){
                                contentElement.text(content);
                            }else{
                                alert( "modification failed" );
                                contentElement.text(oldContent);
                                
                            }

                        }
                        
                    });

}

The above is the most basic usage, the post request enters the path of this url, carries several parameters in the data, and judges the returned result!

Of course, it is impossible to have only these parameters in ajax, and the rest of the parameters are not mentioned here. Interested students can study it by themselves!

There are still problems of synchronization and asynchrony in ajax. Of course, it is asynchronous by default. The so-called synchronization can be understood as single-threaded work. Once it is written as synchronization, the user must wait for the request to complete before performing other operations! 

   async: false to become synchronous

ajax submit form

As we all know, form submission will affect the entire page refresh, but if the form is submitted, the page can not be refreshed, but a part of the page can be refreshed, so our predecessors came up with a wonderful idea, that is to use ajax to submit form, to achieve this double-win goal. Specific examples are as follows:

Commit data without file stream

Personally think that there are two points to pay attention to when submitting a form using ajax: 1. Attach the ID to the form to be submitted, 2: No need to write the action path on the submitted form.

function login() {
            $.ajax({
            // Several parameters need to pay attention to 
                type: "POST", // Method type 
                dataType: "json", // The expected data type returned by the server 
                url: "/users/login" , // url 
                data: $('# form1' ).serialize(),
                success: function (result) {
                    console.log(result); // Print the data returned by the server (for debugging) 
                    if (result.resultCode == 200 ) {
                        alert("SUCCESS");
                    }
                    ;
                },
                error : function() {
                    alert( "Exception!" );
                }
            });
        }

Commit data with file stream

function login() {
                var data=new FormData($( "#addForm" )[0]);
            $.ajax({
            // Several parameters need to pay attention to 
                type: "POST", // method type 
                dataType: "json", // expected data type returned by the server 
                url: "/users/add" , // url 
                cache: false ,     // Uploading files does not need to be cached 
                processData: false , // It needs to be set to false. Because the data value is a FormData object, there is no need to process the data 
                contentType: false , // It needs to be set to false. Because it is a FormData object and has declared the attribute enctype="multipart/form-data" 
                data: data,
                success: function (result) {
                    console.log(result); // Print the data returned by the server (for debugging) 
                    if (result.resultCode == 200 ) {
                        alert("SUCCESS");
                    }
                    ;
                },
                error : function() {
                    alert( "Exception!" );
                }
            });
        }       

 

In fact, there is another way of writing form data through ajax, but it will not be demonstrated here. If you are interested, you can check it online yourself, and welcome to discuss with me! ! !
  

Guess you like

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