Analysis of Ajax principles and advantages and disadvantages, analysis of ajax advantages and disadvantages

Source: Internet
Author: User

Analysis of Ajax principles and advantages and disadvantages, analysis of ajax advantages and disadvantages

1. 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.

2. 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.

3. 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.

In the past 10 hours, the water was not completely disconnected, but the traffic was much lower than before. After 10 hours, the normal traffic was resumed, if it was you, which method would you choose? Obviously the latter.

4. ajax Technologies

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 communicate with the server asynchronously.

4. Use javascript for binding and calling.

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.

5. 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:

Onreadystatechange the event handler of the event triggered by each state change.

The string format of responseText returned data from the server process.

ResponseXML is a DOM-compatible document data object returned by the server process.

Status Code returned from the server, such as common 404 (not found) and 200 (ready)

String information of the status Text accompanied by the status code

ReadyState object status value

0 (not initialized) the object has been created, but has not been initialized (the open method has not been 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 (in data transmission) Some data has been received. Because the response and http headers are incomplete, an error occurs when retrieving part of data through responseBody and responseText,

4. 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 TestAjax () {var data = document. getElementByIdx ("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. getElementByIdx ("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:

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

B. request url and transmitted parameters.

C. Transmission Mode. If the value is false, synchronization is performed. If the value is true, asynchronous transmission is performed. 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.

6. 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, providing a good user experience.

2. Use asynchronous mode to communicate with the server, without interrupting user operations, so as to have a more rapid response capability.

3. Some of the previous server workload can be transferred to the client, and the client's idle capabilities can be used to handle the workload, reduce the load on servers and bandwidth, and save 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.

7. ajax disadvantages

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, 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.

2. Security Issues

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.

3. weak support for search engines.

4. destroys the abnormal mechanism of the program. 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.

5. In addition, 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.

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

8. 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.

9. ajax application example

The above content is a reprinted article written by a senior student. I will give an example of my practical application in the project. This example is as follows: In the duty schedule module of a project I participated in, when you select the person on duty, a tree-based TreeView structure of the contact is displayed. Click the department to which the contact is to be opened, and the contacts under the department are displayed. This is the case. After you select some contacts, the person on duty during the day or night is in the format of "small A, Small B", but now the format is "small A (department 1), Small B (Department 2) here we assume that small A belongs to department 1 and Small B belongs to Department 2. Because the selection of contacts is purely frontend javascript operations, we need to obtain the Department name through the department id in the userlist table of contacts, that is, retrieve the background data through the frontend, this is also described in Series 5. The following code is provided:

Var param = "date = <% = stryear %>/<% = strmonth %>/" + x <% = stryear %> <% = strmonth %> + "& Type = "+ type +" & Other = "+ eval_r (" formData. RBOTHER "+ x + ". value ") +" & ZBRY = "+ eval_r (" formData. RBZBRY "+ x + ". value ") +" & ZBRYID = "+ eval_r (" formData. RBZBRYID "+ x + ". value ") +" & Demo = "+ eval_r (" formData. RBDEMO "+ x + ". value ") +" & id = "+ eval_r (" formData. RBZBID "+ x + ". value "); // The passed parameter var retVal = window. showModalDialog ("chooseUsers. asp? "+ Param, this," dialogWidth = 280px; dialogHeight = 500px; help = no; status = no; scroll = no; resizable = yes ;"); // obtain the contact in the pop-up dialog box // ajax call the server method to obtain the Department name if (retVal ['userid']! = "" & RetVal ['userid']! = Null) // contact id set format: 1, 2, 4 {var PostUrl = ".../Application/CallBoard/GetDepartMentByUid. aspx? UserIDs = "+ objRetVal ['userid'] +" "; // urlxmlHttp = new ActiveXObject (" Microsoft. XMLHTTP "); // create an xmlhttprequest object xmlHttp. open ("POST", PostUrl, false); xmlHttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xmlHttp. send (""); var builder = xmlHttp. responseText; // pass the value back and construct the new format eval_r ("formData. RBZBRY "+ x + ". value = '"+ builder +"' "); // formData. RBZBRY is a text control that displays the new format of on-duty personnel }}

The above section describes the principles, advantages, and disadvantages of Ajax. I hope it will help you!

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.