Ajax Learning Notes

Source: Internet
Author: User

Recently in the study of Ajax asynchronous interaction, there is a very common example of life. Many Web pages have login registration page, in a long time ago, the traditional data validation is required to fill in each item is filled, click the Submit button, data transfer to the background. If your luck is very bad, then embarrassed, the page gives you the hint data format is wrong. The data you've spent a lot of time filling out after the page has been refreshed has been emptied, so you need to step back and fill in the data. Obviously, this kind of user experience is very bad. Therefore, the idea of an asynchronous interaction was born, and the user automatically validates the background with each data entry, noting that the current page is not refreshed, but only partially refreshed.

Let's look at the definition of Ajax: Ajax is all called asynchronous Javascript and XML. It is not a new language, but a comprehensive utilization of existing technology. The essence is to communicate with the server asynchronously, based on the HTTP protocol. Asynchronous means that a program executes without blocking other program execution, in the form of a program's order of execution that does not depend on the writing order of the program itself, but rather on synchronization. The advantage is that it does not block the execution of the program, thereby improving overall execution efficiency. To achieve the purpose of asynchronous interaction, we need to implement the asynchronous object XMLHttpRequest. XMLHttpRequest is a browser built-in object used to communicate with the server in the background (exchanging data) so that we can implement a partial update of the Web page instead of refreshing the entire page.

Simple understanding of the interaction between the front and back, White is six words, request, processing, response . Communication between the browser and the server is subject to certain rules, namely the communication protocol. Common communication protocols are:

A) HTTP, HTTPS Hypertext Transfer Protocol

b) FTP File Transfer Protocol

c) SMTP Simple Mail Transfer Protocol

Communication protocols are not the focus here, we need to understand the HTTP protocol. HTTP protocol is the Hypertext Transfer Protocol, the website is based on the HTTP protocol, such as the site's pictures, CSS, JS, etc. are based on the HTTP protocol for transmission. The HTTP protocol is constrained and regulated by requests from the client to the server (request) and responses from the server to the client (Response). The two common requests in the HTTP protocol are post, GET, and several less common such as put, DELETE.

The client sends a request to the server, which is the request message. The canonical format of the request message is the request line, the request header, and the request body . Such as:

The request message line consists of the request method, the requested URL, and the protocol version, as in the first tag above.

Request headers include:

        • Host:localhost the requested host
        • Cache-control:max-age=0 Control Cache (no-cache| No-store)
        • accept:*/* accepted document MIME type
        • User-agent: Provide access to the site with the type of browser you use, operating system and version, CPU type, browser rendering engine, browser language, browser plugin, and other information identification. The standard format of the browser UA string is: Browser identification (operating system identity; encryption level identification; browser language) rendering engine identity version information
        • Referer: from which URL to jump over
        • Accept-encoding: Acceptable compression format

The request style is the data that is passed to the server.

  

Accordingly, the server response also has a response message. Its canonical format is: status line, response header, response body.

The status line is composed of the protocol version number, the status code, and the status information.

The response headers include:

      • Date: Response time
      • Server: Servers information
      • Content-length: Response Body length
      • Content-type: The MIME type of the response resource

Response Body: The content returned to the client by the service side.

Common server response status codes are:200 for Success , 304 document unmodified, 403 no permissions, 404 Not Found, 500 server error

          

The client and server in the time of data transmission is in byte form, can be understood as text transmission, then the browser needs to know exactly how to parse the text form of data, MIME (Content-type) is to explicitly tell the browser how to handle.

After understanding the client-Server communication protocol, we can proceed with our asynchronous data interaction implementation. To perform data validation with the background, we can direct XMLHttpRequest this asynchronous object to help us implement it.

1, the first is to create an asynchronous object.

In a later version of the browser, it can be created with new XMLHttpRequest (), but in the low version of IE (5, 6) It is created through new ActiveXObject ("Microsoft.XMLHTTP"). The wording of compatibility is:

        

2. After the asynchronous object is successfully created, the request is sent.

Request send needs to set up three parts of the content, there are set request line, set the request header, set the request body three parts. The first is the setting of the request line, as mentioned earlier, the setting of the request line is mainly the way to set the request (the default is a GET request), the requested URL, as well as async (synchronous or asynchronous, the default value is True is asynchronous), the request header settings need to determine what the request method, If the request is get, then you do not need to set the request header, if the request is post, you need to set the request header, the request principal setting is required to pass the parameters, in the Get method is added in the Request line URL, the Post method is written in the request body. Here is a post-mode request sending process:

           

3, the next step is to monitor the server's response status and the state of the asynchronous object.

We can use Onreadystatechange,onreadystatechange as a kind of JavaScript event, meaning to monitor the state of XMLHttpRequest. Here, readystate refers to the response state, which returns the current state of the XMLHTTP request, which indicates a successful request when the value is 4.

                

The status of the monitoring server is through status, and a value of 200 indicates that the server responded successfully. The process is as follows:

        

4, after acquiring the response data to the server, different data are resolved in different ways, and there are common XML and JSON.

Let's take a look at XML first. XML is a markup language, much like HTML, whose purpose is to transmit data with self-descriptive (fixed-format data), such as:

        

The syntax rules for XML are:

A) must have a root element

b) No spaces, no numbers or. Start, case sensitive

c) No cross-nesting

d) attribute double quotation marks (the browser is automatically corrected into double quotes)

e) Special symbols to use entities

f) annotations are the same as HTML

g) Although complex data can be described and transmitted, its resolution is too complex and large, so implementation is rarely used.

JSON: JavaScript Object Notation, another lightweight text data Interchange format, independent of the language. Syntax rules:

A) data in name/value pairs

b) data is separated by commas (the last health/value pair cannot have commas)

c) Save the object in curly brackets, save the array in square brackets

D) Both the name and value need to be enclosed in double quotes

JSON parsing: JSON data in different languages in the transmission, the type is a string, different languages have their own parsing method, need to parse to complete before reading.

a) Javascript parsing method

Json.parse (): Parse a JSON object from a string

Json.stringify (): Parsing a string from a JSON object

JSON-compatible processing json2.js

b) PHP parsing method

Json_encode (): JSON-encodes a variable to return the JSON form of value

Json_decode (): Encodes a JSON-formatted string that accepts a JSON-formatted string and converts it to a PHP variable

Summary: JSON volume is small, easy to parse and efficient, in the actual development becomes the first choice.

Once we understand how these two data are transmitted, we can parse the data retrieved from the database in different ways. Depending on the Content-type attribute in the response header in the response message, it is necessary to determine which method to use, implemented as follows:

        

The getResponseHeader method is to get the value of the specified attribute in the response message, and the foreground decides how to render the result after the data has been processed accordingly. This kind of processing is mostly the concatenation of strings, this process is very cumbersome, we can use the template engine to help us do this kind of thing.

The above mentioned above, in fact, in jquery has helped us to consider the above problems, jquery encapsulates an Ajax method. Introduced as follows:

A) $.ajax ({}) configurable way to initiate AJAX requests

b) $.get () Initiate AJAX requests in Get mode

c) $.post () post-launch Ajax request

d) $ (' form '). Serialize () Serialize the form (that is, format key=val&key=val)

e) Parameter Description:

        • URL: Interface Address
        • Type: Request Method (Get/post)
        • Timeout: Requires a parameter of type number to set the request time-out (in milliseconds)
        • DataType: Server return format
        • Data: Send Request
        • Beforesend: A function that requires a parameter of type function that can modify a XMLHttpRequest object before sending a request, such as adding a custom HTTP header. If you return False in Beforesend, you can cancel this Ajax request.
        • Success: Called after a successful response
        • Error: Called when the response is incorrect
        • Complete: Called when the response completes (both success and failure)

Ajax Learning Notes

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.