How Ajax Works

Source: Internet
Author: User
Tags script tag sql injection browser cache

About the name of Ajax

The full name of Ajax is asynchronous JavaScript and XML, where asynchronous is asynchronous and differs from the way in which traditional web development uses synchronization.

About synchronous and asynchronous

Asynchronous transmission is a character-oriented transmission, its unit is a character, and synchronous transmission is a bit-oriented transmission, its unit is frame, it is transmitted when the receiver and the sender's clock is consistent.

Specifically, asynchronous transmission is the transfer of bits into groups. Typically each group is a 8-bit character, in the head and tail of each group has a start bit and a stop bit, it in the transmission process the receiver and the sender's clock does not require the same, that is, the sender can send these groups at any time, and the receiver does not know when it arrives. One of the most obvious examples is the computer keyboard and host communication, press a key while sending a 8-bit ASCII code to the host, the keyboard can send code at any time, depending on the user's input speed, the internal hardware must be able to receive a typed character at any moment. This is a typical asynchronous transfer process. There is a potential problem with asynchronous transmissions, where the receiver does not know when the data will arrive. The first bit has passed before it detects and responds to the data. It's like someone coming up from behind unexpectedly and talking to you, and you missed out on the first few words before you could react. Therefore, each asynchronous transfer of information begins with a starting bit, which notifies the receiver that the data has arrived, giving the receiver the time to respond, receive, and cache the data bits, and at the end of the transfer, a stop bit indicates the termination of the transmission information. By convention, a line that is idle (without transmitting data) actually carries a signal that represents a binary 1. The start bit of the step transfer makes the signal 0, and the other bits make the signal vary with the data being transmitted. Finally, the stop bit causes the signal to change back to 1, and the signal remains at the next start bit. For example, on the keyboard the number "1", according to the 8 bit of extended ASCII encoding, will be sent "00110001", at the same time need to precede the 8 bit with a starting bit, the back of a stop bit.

The bit groupings for synchronous transmissions are much larger. Instead of sending each character independently, each character has its own start and stop bits, but it combines them together to send. We call these combinations a data frame, or simply a frame.

The first part of the data frame contains a set of synchronized characters, which is a unique bit combination, similar to the starting bit mentioned earlier, to inform the receiver that a frame has arrived, but it also ensures that the receiver's sampling speed and the speed of the bit are consistent, so that the sending and receiving parties enter the synchronization.

The last part of the frame is a frame end tag. Like a synchronous character, it is also a unique bit string, similar to the stop bit mentioned earlier, to indicate that there is no other data to arrive at the beginning of the next frame.

Synchronous transmissions are often much faster than asynchronous transmissions. The receiver does not have to start and stop the operation for each character. Once a frame synchronization character is detected, it receives them when the next data arrives. In addition, the overhead of synchronous transmission is relatively low. For example, a typical frame might have 500 bytes (that is, 4000 bits) of data, which might contain only 100 bits of overhead. At this point, the increased bit bit increases the total number of bits transmitted by 2.5%, which is much smaller than the 25 increment in asynchronous transmissions. As the actual bit of data in the data frame increases, the percentage of overhead bits will be reduced accordingly. However, the longer the data bit, the greater the buffer required to cache the data, which limits the size of one frame. In addition, the larger the frame, the longer it occupies the continuous time of the transmission media. In extreme cases, this will cause other users to wait too long.

Once you understand the concepts of synchronization and asynchrony, you should be clear about why Ajax can improve the user experience, which takes the form of asynchronous requests. For example, if your home is now in the community because of some situation and water, now the relevant departments announced two programs, one is completely water off 8 hours, in this 8 hours completely water, 8 hours after the return to normal. Two is not completely water off 10 hours, in this 10 hours of water is not completely broken, but the flow is much smaller than the original, after 10 hours to return to normal flow, then, if it is you you will choose which way? Obviously the latter.

The technology that Ajax contains

We all know that Ajax is not a new technology, but a combination of several original technologies. It is a combination of the following technologies.

1. Use CSS and XHTML to represent.

2. Use the DOM model for interactive and dynamic display.

3. Use XMLHttpRequest to communicate with the server asynchronously.

4. Use JavaScript to bind and invoke.

In the above technology, in addition to the XMLHttpRequest object, all other technologies are based on web standards and has been widely used, xmlhttprequest although not yet accepted by the website, but it is a fact of the standard, Because it is currently supported by almost all major browsers.

Ajax principles and XMLHttpRequest objects

The principle of Ajax is simply to send an asynchronous request to the server via the XMLHttpRequest object, get the data from the server, and then use JavaScript to manipulate the DOM and update the page. One of the most critical steps is getting the request data from the server. To understand this process and principle, we must have some knowledge of xmlhttprequest.

XMLHttpRequest is the core mechanism of Ajax, which was first introduced in IE5 and is a technique that supports asynchronous requests. Simply put, JavaScript can request and process responses to the server in a timely manner without blocking the user. Achieve a no-refresh effect.

So let's start with XMLHttpRequest and see how it works.

First, let's take a look at the properties of the XMLHttpRequest object.

Its properties are:

onReadyStateChange event handlers for events that are triggered by each state change.

ResponseText the string form of the data returned from the server process.

Responsexml a DOM-compatible document data object that is returned from the server process.

Status number codes returned from the server, such as common 404 (not Found) and 200 (ready)

Status Text string information accompanying the state code

ReadyState Object State Value

0 (uninitialized) object has been established but not initialized (the open method has not been called)

1 (Initialize) object has been established, the Send method has not been called

2 (send data) The Send method has been called, but the current state and HTTP headers are unknown

3 (data transfer) has received some of the data, because the response and HTTP header is not complete, then through Responsebody and ResponseText to obtain some of the data will be error,

4 (complete) The data is received, at which time the complete response data can be obtained by Responsexml and ResponseText

However, because there are differences between browsers, creating a XMLHttpRequest object may require different methods. This difference is mainly between IE and other browsers. The following is a more standard way to create a XMLHttpRequest object.

function Createxmlhttp () {

Non-IE browser creates XMLHttpRequest object
if (window. XMLHttpRequest) {
XMLHTTP = new XMLHttpRequest ();
}

IE Browser creates XMLHttpRequest object
if (window. ActiveXObject) {
try {
XMLHTTP = new ActiveXObject ("Microsoft.XMLHTTP");
}
catch (e) {
try {
XMLHTTP = new ActiveXObject ("MSXML2. XMLHTTP ");
}
catch (ex) {}
}
}
}

function Ustbwuyi () {

var data = document.getElementById ("username"). Value;
Createxmlhttp ();
if (!xmlhttp) {
Alert ("Create XMLHTTP Object Exception! ");
return false;
}

Xmlhttp.open ("POST", url, false);

Xmlhttp.onreadystatechange = function () {
if (xmlhttp.readystate = = 4) {
document.getElementById ("user1"). InnerHTML = "Data loading ...";
if (Xmlhttp.status = = 200) {
document.write (Xmlhttp.responsetext);
}
}
}
Xmlhttp.send ();
}


As shown above, the function first checks the overall state of the XMLHttpRequest and ensures that it has been completed (readystatus=4), that is, the data has been sent. The request status is then queried based on the server's settings, and if everything is ready (status=200), perform the actions required below.

For XMLHttpRequest two methods, open and send, where the Open method specifies:

A, the type of data that is submitted to the server, that is, post or get.

b, the requested URL address and the passed parameters.

C, transmission mode, false is synchronous, true is asynchronous. The default is true. In the case of asynchronous communication (true), the client does not wait for the server to respond, and if it is synchronous (false), the client waits until the server returns the message before performing other operations. We need to specify the synchronization according to the actual needs, in some pages, may make multiple requests, even the organization has a plan to form a large-scale high-intensity request, the next one will overwrite the previous one, this time of course to specify the synchronization mode.

The Send method is used to send the request.

Knowing the XMLHttpRequest workflow, we can see that XMLHttpRequest is completely used to send a request to the server, its role is limited to this, but its role is the key to the entire AJAX implementation, because Ajax is nothing more than two processes, Make requests and respond to requests. And it's completely a client-side technology. And XMLHttpRequest is dealing with the server side and client communication problems, so it is so important.

Now, we probably have an understanding of the principles of Ajax. We can think of the server as a data interface, which returns a plain text stream, of course, the text stream can be in XML format, can be HTML, can be JavaScript code, can be just a string. At this time, XMLHttpRequest to the server side to request this page, the server side writes the results of the text to the page, which is the same as the normal web development process, the difference is that the client asynchronously obtains this result, is not directly displayed on the page, but first by the JavaScript processing, Then the page appears again. As for many of the Ajax controls that are now popular, such as Magicajax, you can return other data types such as datasets, but only encapsulate the results of this process, and they are not much different in nature.

Ajax method parameters in jquery are always remembered, here is a record.

1.url:
Requires that the requested address be sent as a parameter of type string (the current page address is assumed to be the default).

2.type:
A parameter of type string is required, and the request method (post or get) defaults to get. Note Other HTTP request methods, such as put and delete, can also be used, but only some browsers support it.

3.timeout:
Requires a parameter of type number to set the request time-out (in milliseconds). This setting overrides the global setting of the $.ajaxsetup () method.

4.async:
Requires a parameter of type Boolean, which is set to True by default and all requests are asynchronous requests. If you need to send a synchronization request, set this option to false. Note that the synchronization request locks the browser, and the user's other actions must wait for the request to complete before it can be executed.

5.cache:
A parameter that is required to be of type Boolean, which defaults to True (False when datatype is a script), and set to false will not load the request information from the browser cache.

6.data:
Requires data to be sent to the server as an object or a string of type parameters. If it is not already a string, it is automatically converted to a string format. The GET request will be appended to the URL. To prevent this automatic conversion, you can view the ProcessData option. The object must be in key/value format, for example {foo1: "Bar1", Foo2: "Bar2"} to &foo1=bar1&foo2=bar2. In the case of arrays, jquery automatically corresponds to the same name for different values. For example {foo:["Bar1", "Bar2"]} is converted to &FOO=BAR1&FOO=BAR2.

7.dataType:
Requires a parameter of type string that expects the data type returned by the server. If not specified, jquery automatically returns Responsexml or ResponseText based on the HTTP packet mime information and is passed as a callback function parameter. The following types are available:
XML: Returns an XML document that can be processed with jquery.
HTML: Returns plain text HTML information, and the included script tag is executed when the DOM is inserted.
Script: Returns plain text JavaScript code. Results are not automatically cached. Unless the cache parameter is set. Note When you make a remote request (not under the same domain), all post requests are converted to get requests.
JSON: Returns the JSON data.
JSONP:JSONP format. When a function is called using the Sonp form, for example Myurl?callback=?,jquery will automatically replace the latter "?" is the correct function name to execute the callback function.
Text: Returns a plain text string.

8.beforeSend :
requires a parameter of type function that can modify the functions of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. If you return False in Beforesend, you can cancel this Ajax request. The XMLHttpRequest object is the only parameter.
            Function (XMLHttpRequest) {
                this;  // The options parameter
           }
9 that was passed when the AJAX request was invoked. Complete :
requires a parameter of type function that is called when the request is completed (called when the request succeeds or fails). Parameters: The XMLHttpRequest object and a string that describes the successful request type.
          function (XMLHttpRequest, textstatus) {
              this;   //Options parameters passed when calling this Ajax request
         }

10.success : Requires a parameter of type function, the callback function called after the request succeeds, there are two parameters.
         (1) The data returned by the server and processed according to the datatype parameter.
         (2) A string describing the status.
         function (data, textstatus) {
            //data may be xmldoc, jsonobj, HTML, text, and so on
             this; //The options parameter passed when calling this Ajax request
         }

11.error:
The function that is called when the request fails with a parameter that is required as a function type. The function has 3 parameters, the XMLHttpRequest object, the error message, and optionally the error object being captured. The Ajax event functions are as follows:
function (XMLHttpRequest, textstatus, Errorthrown) {
Normally textstatus and Errorthrown only one of them contains information
This Options parameters passed when calling this Ajax request
}

12.contentType:
A parameter of type string is required, and when the message is sent to the server, the content encoding type defaults to "application/x-www-form-urlencoded". This default value is suitable for most applications.

13.dataFilter :
requires a function type parameter to preprocess the original data returned by Ajax. Provides data and type two parameters. Data is the original data returned by Ajax, and type is the datatype parameter that is provided when Jquery.ajax is called. The value returned by the function will be further processed by jquery.
            function (data, type) {
                //Return to processed data
                 return data;
           }

14.dataFilter:
A function that requires the preprocessing of the original data returned by Ajax, as a parameter of the function type. Provides data and type two parameters. Data is the original data returned by Ajax, and type is the datatype parameter that is provided when Jquery.ajax is called. The value returned by the function will be further processed by jquery.
function (data, type) {
Returns the processed data
return data;
}

15.global:
Requires a parameter of type Boolean, which is true by default. Indicates whether global AJAX events are triggered. Setting to FALSE will not trigger global AJAX events, Ajaxstart or ajaxstop can be used to control various AJAX events.

16.ifModified:
A parameter of type Boolean is required, and the default is False. Get new data only when the server data changes. Server data changes are based on the last-modified header information. The default value is False, which ignores header information.

17.jsonp:
Requires a parameter of type string to override the name of the callback function in a JSONP request. This value is used instead of the "callback=?" The "callback" part of the URL parameter in this get or POST request, such as {jsonp: ' onjsonpload ', causes the "onjsonpload=?" passed to the server.

18.username:
A parameter of type string that is required to respond to the user name of the HTTP access authentication request.

19.password:
A parameter of type string that is required to respond to the password for HTTP access authentication request.

20.processData:
Requires a parameter of type Boolean, which is true by default. By default, the data sent is converted to an object (technically not a string) to match the default content type "application/x-www-form-urlencoded". Set to False if you want to send DOM tree information or other information that you do not want to convert.

21.scriptCharset:
A parameter of type string is required and is used to force the character set (charset) only if the request is datatype as "JSONP" or "script" and the type is get. Typically used when local and remote content encodings are different.

1 $ (function () {2$ (' #send '). Click (function () {3 $.ajax ({4Type: "GET",5URL: "Test.json",6Data: {username:$ ("#username"). Val (), content:$ ("#content"). Val ()},7DataType: "JSON",8 success:function (data) {9$ (' #resText '). empty ();//empty everything inside the restext.Tenvar html = ' ';  One $.each (data, function (Commentindex, comment) { AHTML + = ' <div class= "comment" >] -+ ': ] -+ ' </p></div> '; the                          }); -$ (' #resText '). HTML (HTML); -                       } -          }); +     }); -});

The advantages of Ajax

Ajax to bring us the benefits of all of you are basically deep experience, here I only briefly say a few points:

1, the biggest point is that the page does not refresh, in the page and the server to communicate with the user experience is very good.

2, using the asynchronous way to communicate with the server, do not need to interrupt the user's operation, with more rapid response.

3, can transfer the work of some previous server to the client, take advantage of the client idle ability to handle, reduce the burden of server and bandwidth, save space and broadband rental cost. and reduce the burden on the server, the principle of Ajax is "on-demand data", can minimize redundancy requests, and response to the burden on the server.

4, based on standardized and widely supported technology, do not need to download plug-ins or small programs.

Disadvantages of Ajax

Let me focus on the drawbacks of Ajax, because most of the things we pay attention to are the benefits of Ajax, such as the improvement of the user experience. And the shortcomings of Ajax have been neglected.

The drawbacks of Ajax described below are inherently generated.

1, Ajax killed the back button, that is, the browser fallback mechanism of destruction. The Back button is an important feature of a standard web site, but it does not work well with JS. This is a serious problem with Ajax, because users often want to be able to undo the previous operation by going backwards. So is there any way to do this question? The answer is yes, using Gmail know, Gmail under the Ajax technology to solve the problem, in Gmail can be back, but it does not change the mechanism of Ajax, it is only a relatively stupid but effective way, that is, the user click the Back button to access the history To reproduce the changes on the page by creating or using a hidden iframe. (for example, when a user clicks back in Google Maps, it searches in a hidden iframe and then reflects the search results on an AJAX element to restore the application state to its current state.) )

However, although this problem can be solved, but the development cost of it is very high, and the AJAX framework required by the rapid development is a divergence. This is a very serious problem caused by Ajax.

2, security issues

Technology also poses new security threats to IT companies, and Ajax technology is just like building a direct channel to enterprise data. This allows developers to inadvertently expose more data and server logic than ever before. The logic of Ajax can be hidden from the client's security scanning technology, allowing hackers to create new attacks from remote servers. And Ajax also makes it difficult to avoid some known security weaknesses, such as cross-site footstep attacks, SQL injection attacks, and credentials-based security vulnerabilities.

3, the support of the search engine is weaker.

4. The abnormal mechanism of the program is destroyed. At least for now, these Ajax frameworks, like Ajax.dll,ajaxpro.dll, can disrupt the program's exception mechanism. On this issue, I have encountered in the development process, but looked at the Internet almost no relevant introduction. Then I did a test by myself, using Ajax and the traditional form submission mode to delete a piece of data ... It has brought us a lot of difficulties in debugging.

5, in addition, like some other aspects of the problem, such as violating the URL and resource positioning of the original intention. For example, I give you a URL address, if you use Ajax technology, perhaps you see below the URL address and what I see under this URL is different. This is contrary to the original intention of resource positioning.

6, some handheld devices (such as mobile phones, PDAs, etc.) are not very good to support Ajax, for example, we open the browser on the mobile phone using AJAX technology site, it is currently not supported, of course, this problem and we do not have much to do with.

Several frameworks of Ajax

The more Ajax frameworks we use today are mainly Ajax.dll,ajaxpro.dll,magicajax.dll and Microsoft's Atlas framework. Ajax.dll and Ajaxpro.dll These two frameworks are not very different, and Magicajax.dll just package more, for example, it can directly return the dataset dataset, as we have said before, Ajax is returning a string, Magicajax just encapsulated it. But this feature can bring us a lot of convenience, for example, our page has a list, and the list of data is constantly changing, then we can use Magicajax to deal with, the operation is very simple, after adding Magicajax, The list control to be updated is placed within the Magicajax control, and the time to define the update interval within the pageload is OK, and the principle of Atlas is similar to Magicajax. However, one of the problems to be aware of is that these frameworks only support IE, do not do browser-compatible aspects of the processing, with the anti-compilation tools to see their code can be known.

In addition to these frameworks, the more common way we use them is to create XMLHttpRequest objects ourselves, which is more flexible than the previous frameworks. In addition, here also mention the aspnet2.0 of the asynchronous callback interface, it can also be implemented as Ajax partial non-flush, but its implementation is actually based on the XMLHttpRequest object, but also only support IE, of course, this is Microsoft's competitive strategy.

Ajax Example

Verify that the user name is registered.

There are two ways of using

1 Ajax.dll

2 Write XMLHttpRequest Object yourself

Thank you for this article: http://www.cnblogs.com/ustbwuyi/archive/2007/02/08/645061.html#2215165

How Ajax Works

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.