Basic Ajax knowledge

Source: Internet
Author: User

Before writing this article, I once wrote an article about AJAX technology, but it involves a narrow range of aspects. It rarely involves null in the background, principles, advantages and disadvantages of AJAX technology. The background of this article is that the company needs to train internal programmers. The project manager found me and asked me about the training topics. Considering the previous WEB development technologies such as Javascript and CSS, therefore, we decided to make a systematic training for AJAX, so this article is actually a training material.

Background of AJAX technology

It is undeniable that the popularity of ajax technologies has benefited from the vigorous promotion of google. It is precisely because google earth, google suggest, gmail, and other widely used ajax technologies that have given rise to the popularity of ajax. Microsoft was also very embarrassed because Microsoft had invented the key ajax technology as early as 97 years ago and began to support XmlHttpRequest objects when IE5 was launched in 99 years, in addition, Microsoft has already begun to apply ajax in some of its products, such as some applications in the MSDN website menu. Unfortunately, I don't know what the idea is. After Microsoft invented the core ajax technology, it did not see its potential for development and promotion, but put it on hold. For this reason, I personally think it is very strange, because Microsoft's resources and its strategic vision should not see the prospect of ajax technology, the only explanation may be that the disappearance of Netscape, its main competitor, made it paralyzed and dull, for example, IBM has made a mistake in Microsoft's strategy. It was this mistake that made google a leader in ajax, its current competitor. In fact, google's current leader in ajax technology cannot be achieved by Microsoft, this will also be mentioned later when I talk about ajax defects. Now Microsoft is aware of this problem, so it has started to catch up in the ajax field, for example, launching its own ajax framework atlas, and in. NET2.0 also provides an interface for implementing asynchronous callback, that is, the ICallBack interface. Why is Microsoft so nervous about its ajax lag? Now let's analyze the hidden significance behind ajax technology.

Significance of ajax technology

We have made more or less contact with or applied ajax in our daily development. When talking about the significance of ajax technology, the most important thing we pay attention to is undoubtedly to improve the user experience. However, if we combine the development trend of computers and the Internet in the future, we will find that ajax technology exactly represents this trend in some aspects. Why? We know that desktop software has been dominant since the emergence of computers, but the emergence and success of the Internet have led to a subtle change. A considerable number of people believe that sooner or later, data and computer software will be transferred from the desktop to the Internet. That is to say, in the future, computers may discard heavy hard drives and directly obtain data and services from the internet. I remember when I went to college, a professor gave us lessons, I have imagined such a scenario. Maybe there will be no additional software or programs on the desktop of a computer in the future, but there will only be one IE. Although we seem to be far away from this day, there are still many problems to solve, but I think this is not a dream, but a reality that will be realized sooner or later. The main problem is that the connection to the Internet is unstable, and no one wants to watch their computers download 1.1 drops of data from the server. Does ajax solve this problem, to be honest, ajax solves this problem rather than simply masks it. It serves as a buffer between the server and the client, so that users may mistakenly think that the service is not interrupted. To be precise, ajax does not speed up downloading data from the server, but does make the wait less frustrating. However, this is enough to have a huge impact and vibration. It actually has a huge impact on desktop software. I will use an example to illustrate this. We can compare Outlook Express and Gmail. The former is a typical desktop software, and the latter is the B/S Mode Implemented by ajax, in fact, the latter has gradually replaced the former. Gmail has almost no difference in the functions of Outlook Express when sending and receiving emails, and it does not need to install a client program. This is why Microsoft is so scared about the impact of ajax, and in its recent investigation, google is seen as one of the main reasons for their competitors over the next decade. Of course, this change will not eliminate all desktop software, and there is no existing browser that can process complex images like PhotoShop and other desktop programs. However, we cannot ignore the impact and impact it brings.

Ajax name

The full name of ajax is Asynchronous JavaScript and XML. Asynchronous is Asynchronous, which is different from the synchronous method used in traditional web development.

About synchronous and asynchronous

Asynchronous transmission is character-oriented transmission. Its unit is character, while synchronous transmission is bit-oriented transmission. Its unit is bytes, it requires that the receiver and the sender's clock be consistent during transmission.

Specifically, asynchronous transmission divides bits into groups for transmission. Generally, each group is an 8-character group with a starting and ending bits at the header and tail of each group. It does not require the same receiver and sender clock during the transfer process, that is to say, the sender can send these groups at any time, and the receiver does not know when it will arrive. One of the most obvious examples is the communication between the computer keyboard and the host. Press the next key to send an 8-bit ASCII code to the host. The keyboard can send code at any time, this depends on the user input speed. The internal hardware must be able to receive a typed character at any time. This is a typical asynchronous transmission process. Asynchronous transmission has a potential problem, that is, the receiver does not know when the data will arrive. Before it detects the data and responds, the first bit has passed. This is like someone coming up and talking to you unexpectedly, and you missed the first few words before you could respond. Therefore, the information transmitted asynchronously starts with a starting bit and notifies the recipient that the data has arrived. This gives the recipient the time to respond, receive, and cache data bits; at the end of the transfer, a stop bit indicates the termination of the transfer information. By convention, idle (no data is transmitted) lines actually carry a Signal Representing Binary 1. The Start bit of the Step transmission changes the signal to 0, and other bits change the signal with the transmitted data information. Finally, the stop position changes the signal back to 1, and the signal remains till the next start position. For example, the number "1" on the keyboard, according to the 8-bit extended ASCII encoding, will send "00110001", at the same time need to add a start bit before the 8-bit, followed by a stop bit.

The bit groups for synchronous transmission are much larger. It does not send each character independently. Each character has its own Start and Stop bits, but sends them together. We call these combinations a data frame or frame for short.

The first part of a data frame contains a set of synchronization characters. It is a unique bit combination, similar to the Start bit mentioned earlier, used to notify the recipient that a frame has arrived, however, it can also ensure that the sampling speed of the receiver is consistent with the bit arrival speed, so that the receiving and receiving sides can synchronize.

The last part of a frame is a frame end mark. Like synchronization characters, it is also a unique Bit String, similar to the stop bit mentioned above, used to indicate that there is no data to be reached before the next frame starts.

Synchronous transmission is usually much faster than asynchronous transmission. The receiver does not have to start or stop each character. Once the frame synchronization characters are detected, it receives them when the next data arrives. In addition, the cost of synchronous transmission is also relatively small. For example, a typical frame may have 500 bytes (4000 bits) of data, which may only contain 100 bits of overhead. At this time, the added bit increases the total number of transmitted BITs by 2.5%, which is much smaller than the value-added value of 25% in asynchronous transmission. As the actual data bit in the data frame increases, the percentage of overhead bit will be reduced accordingly. However, the longer the bit length of the data, the larger the buffer required for caching the data, which limits the size of a frame. In addition, the larger the frame, the longer it occupies the continuous time of the transmitted media. In extreme cases, this will cause other users to wait too long.

After learning about the concepts of synchronization and Asynchronization, we should be clear about why ajax can improve user experience. It uses asynchronous requests. For example, if the current residential area in your home is facing water stop due to a certain situation, the relevant departments have published two solutions: one is to stop water for 8 hours, the water has been completely stopped in these eight hours, and will return to normal after 8 hours. Second, the water was not completely stopped for 10 hours, but the water was not completely interrupted during the 10 hours, but the traffic was much smaller than the original one. After 10 hours, the normal traffic was restored, if it was you, which method would you choose? Obviously the latter.

Technologies included in ajax

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

  1. CSS and XHTML are used for representation.
  2. Use the DOM model for interaction and dynamic display.
  3. Use XMLHttpRequest to perform asynchronous communication with the server.
  4. Use javascript to bind and call.

In the above technical procedures, apart from XmlHttpRequest objects, all other technologies are based on web standards and have been widely used. Although XMLHttpRequest has not yet been adopted by W3C, but it is already a standard of fact, because almost all mainstream browsers currently support it.

Ajax principles and XmlHttpRequest objects

The principle of Ajax is simply to use the XmlHttpRequest object to send asynchronous requests to the server, obtain data from the server, and then use javascript to operate the DOM to update the page. The most critical step is to obtain request data from the server. To understand the process and principles, we must understand XMLHttpRequest.

XMLHttpRequest is the core mechanism of ajax. It is first introduced in ie5. it is a technology that supports asynchronous requests. Simply put, javascript can promptly request and process responses to the server without blocking users. Achieve the effect of refreshing.

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

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

Its attributes include:

Attribute Description
Onreadystatechange The event handler of the event triggered by each state change.
ResponseText The string format of the data returned by the server process.
ResponseXML The DOM-compatible document data object returned by the server process.
Status Number Code returned from the server, such as common 404 (not found) and 200 (ready)
Status Text String information of the accompanied status code
ReadyState Object status value

Object status value:

ReadyState Description
0 (not initialized) Object created but not initialized (open method not called)
1 (initialization) The object has been created and the send method has not been called
2 (send data) The send method has been called, but the current status and http header are unknown.
3 (data transmission in progress) Some data has been received. Because the response and http headers are incomplete, an error occurs when you obtain some data through responseBody and responseText.
4 (finished) After receiving the data, you can use responseXml and responseText to obtain the complete response data.

However, because of the differences between browsers, creating an XMLHttpRequest object may require different methods. This difference is mainly reflected in IE and other browsers. The following is a standard method for creating an XMLHttpRequest object.

Function CreateXmlHttp () {// create the XmlHttpRequest object if (window. xmlHttpRequest) {xmlhttp = new XmlHttpRequest ();} // create the 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 ("An error occurred while creating the xmlhttp object! "); 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 XMLHttpRequest and ensures that it has been completed (readyStatus = 4), that is, the data has been sent. Then, query the Request status based on the server settings. If everything is ready (status = 200), perform the following operations.

For the XmlHttpRequest methods, open and send, the open method specifies:

  1. Type of data submitted to the server, that is, post or get.
  2. The request url and the passed parameters.
  3. Transmission Mode. "false" indicates synchronization, and "true" indicates asynchronous transmission. The default value is true. If it is an asynchronous communication method (true), the client will not wait for the server to respond; if it is a synchronous mode (false), the client will wait until the server returns a message before executing other operations. We need to specify the synchronization mode based on actual needs. In some pages, multiple requests may be sent, or even highly-intensive requests with organized and planned structures, the other one will overwrite the previous one. In this case, you must specify the synchronization mode.

The Send method is used to Send requests.

After learning about the XMLHttpRequest workflow, we can see that XMLHttpRequest is completely used to send a request to the server. Its role is also limited to this, but its role is the key to the entire ajax implementation, because ajax is nothing more than two processes, sending requests and responding to requests. And it is completely a client technology. XMLHttpRequest is so important because it handles the communication between the server and the client.

Now we can have a general understanding of the principles of ajax. We can regard the server as a data interface, which returns a plain text stream. Of course, this text stream can be in XML format, Html, or Javascript code, it can also be a string. At this time, XMLHttpRequest requests this page from the server, and the server writes the text results to the page. This is the same as the normal web development process, after the client asynchronously obtains this result, it is not directly displayed on the page, but processed by javascript first and then displayed on the page. As for many popular ajax controls such as magicajax, other data types such as DataSet can be returned, but the results encapsulated by this process are essentially no big difference.

Advantages of ajax

The benefits brought to us by Ajax are basically profound experiences. Here I will only briefly talk about the following points:

  1. The biggest difference is that the page is refreshed and communicates with the server on the page, which provides a good user experience.
  2. Communication with the server in asynchronous mode does not need to interrupt user operations and provides more rapid response capabilities.
  3. The previous server workload can be transferred to the client, and the client's idle capabilities can be used to reduce the burden on servers and bandwidth, saving space and bandwidth rental costs. In addition, it reduces the burden on the server. The ajax principle is to "retrieve data on demand", which can minimize the burden on the server caused by redundant requests and responses.
  4. Based on standardized and widely supported technologies, you do not need to download plug-ins or applets.
Disadvantages of ajax

Next I will focus on the ajax defects, because most of our daily attention is the benefits brought to us by ajax, such as the improvement of user experience. The defects caused by ajax are ignored.

The ajax defects described below are inherent in nature.

  1. Ajax kills the back button
  2. Ajax kills the back button, which destroys the browser's back-up mechanism. The back button is an important feature of a standard web site, but it cannot cooperate well with js. This is a serious problem caused by ajax, because users often want to cancel the previous operation by going back. Is there any way to solve this problem? The answer is yes. If you have used Gmail, the ajax technology used in Gmail solves this problem. You can withdraw from Gmail. However, it cannot change the ajax mechanism either. It is just a stupid but effective method, that is, when the user clicks the back button to access the history, create or use a hidden IFRAME to reproduce changes on the page. (For example, when a user clicks back in Google Maps, it searches in a hidden IFRAME and then reflects the search result to the Ajax element, to restore the application status to the current state .) However, although this problem can be solved, it brings about a very high development cost, which is different from the rapid development required by the ajax framework. This is a very serious problem caused by ajax.

  3. Security Questions
  4. Technology also brings new security threats to IT enterprises. ajax technology is like establishing a direct channel for enterprise data. This allows developers to inadvertently expose more data and server logic than before. The ajax logic can be hidden from the client's security scanning technology, allowing hackers to create new attacks from remote servers. There are also known security vulnerabilities that cannot be avoided by ajax, such as cross-site scripting attacks, SQL injection attacks, and credentials-based security vulnerabilities.

  5. Weak support for search engines
  6. Destroys the program exception mechanism.
  7. At least from the current perspective, ajax frameworks such as ajax. dll and ajaxpro. dll will destroy the program's exception mechanism. I have encountered this problem during the development process, but I have found that there is almost no relevant introduction on the Internet. Later, I did a test to delete a piece of data in ajax and traditional form submission modes ...... It brings great difficulties to our debugging.

  8. Other problems
  9. In addition, there are some other problems, such as violating the original intention of url and resource positioning. For example, if ajax technology is used, what you see under the url address is different from what I see under the url address. This is contrary to the original intention of resource positioning.

  10. Some handheld devices (such as mobile phones and PDAs) cannot support ajax yet.
  11. Some handheld devices (such as mobile phones and PDAs) do not support ajax yet. For example, when we open a website using ajax technology on a mobile browser, it does not currently support ajax, of course, this problem has nothing to do with us.

Several ajax frameworks

Currently, we have adopted many ajax frameworks, including ajax. dll, ajaxpro. dll, magicajax. dll, and Microsoft's atlas framework. Ajax. dll and Ajaxpro. the two dll frameworks have little difference, while magicajax. dll is more encapsulated. For example, it can directly return the DataSet. As we have already said, ajax returns strings, while magicajax only encapsulates them. However, this feature can bring us great convenience. For example, if there is a list on our page and the data in the list is constantly changing, we can use magicajax to process it, the operation is very simple. After magicajax is added, the list control to be updated is placed in the magicajax control, and the update interval defined in pageload is OK. The principle of atlas is similar to that of magicajax. However, it is worth noting that these frameworks only support IE and do not handle browser compatibility. You can check their code with decompilation tools.

In addition to these frameworks, we usually use a lot of ways to create xmlHttpRequest objects by ourselves, which is more flexible than the previous frameworks. In addition, the asynchronous callback interface provided by aspnet2.0 is also mentioned here. Like ajax, it can also implement local refreshing, but its implementation is actually based on the xmlhttprequest object, in addition, only Internet Explorer is supported. Of course, this is a competitive strategy of Microsoft.

Related Article

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.