How Ajax Works

Source: Internet
Author: User
first, the background of Ajax Technology

It is undeniable that the popularity ofAjax technology has benefited from Google's strong promotion, it is because of Google Earth, Google suggest and Gmail, and other Ajax technology for the wide application, the emergence of Ajax 's popularity. This is also embarrassing for Microsoft, as early as 97, Microsoft has invented the key technology in Ajax , and in 99 when IE5 launched, it began to support the XMLHttpRequest object , And Microsoft has already started to apply Ajaxto some of its products, such as some of the apps in the MSDN Web site menu. Unfortunately, I do not know what the idea was, when Microsoft invented the core technology of Ajax , and did not see its potential to develop and promote, but put it aside. For this, I personally feel very strange, because Microsoft's resources and its strategic vision, should not see the future of Ajax Technology, the only explanation may be because its main competitor Netscape the disappearance of it makes it become paralyzed and dull, After all, Giants also have naps, such as IBM's past mistakes in Microsoft's strategy. It was this mistake that made its current competitor Google's leading position in Ajax , and the fact that Google's current lead in Ajax technology was beyond Microsoft's reach, which I told you later The Ajax flaw will also be mentioned. Now Microsoft is aware of the problem, so it's also starting to catch up in the Ajax World, like introducing its own AJAX framework, Atlas, and in. NET2.0 also provides an interface for implementing asynchronous callbacks, the Icallback interface. So why is Microsoft so nervous about its backwardness in Ajax ? Now let's analyze the deep meaning behind Ajax Technology.

Second, what is Ajax

Ajax , "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML), refers to a web development technique that creates interactive Web applications. Ajax includes implementing Web pages using XHTML and CSS standards, using the DOM for dynamic display and interaction, using XML for data exchange and processing, and finally binding and processing all data using JavaScript. Ajax Offload Some of the workload of the server to the client, using some of the client's ability to process the data, reduce the user's actual and psychological waiting time, the user is not encountered because the page refresh caused the browser long time blank, or even stop responding bad results, which gives the user the best experience. Ajax is based on standardized XML, is widely used and supported, and is conducive to maintenance and modification. Ajax makes it easy to invoke external data, and Ajax can be used to get data when the page is separated from the data.

Third, the technology thatAjax 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.

Iv.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. with a clearer understanding of how Ajax Works

How Ajax Works ">

How the XMLHttpRequest works.
The properties of the XMLHttpRequest object 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)
StatusText string information accompanying the status 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) received part of the data, because the response and HTTP header is not complete, then through the 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

because there are differences between browsers, create a XMLHttpRequest objects may require different methods. This difference is mainly between IE and other browsers. Here's a more standard way to create a xmlhttprequest Object

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.
D, the Send method is used to send the request .

From 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 the Ajax is nothing more than two processes, making requests and responding 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.

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 the many 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, which in essence they are not much different.

V. Advantages and disadvantages ofAjax

Advantages of Ajax :
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, you can transfer the work of some previous servers to the client, using the client's idle ability to handle, reduce the burden of server and bandwidth, save space and wide with rental costs. and reduce the burden on the server, the principle ofAjax 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 :
Because most of the times we pay attention to the benefits of Ajax to us such as the improvement of 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's just a dumb but effective way to reproduce changes on a page by creating or using a hidden iframe when the user clicks the Back button to access the history. (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, andAjax 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 search index support is weaker.
4. The abnormal mechanism of the program is destroyed. At least for now, Ajax Pro.dll, like ajax. dll , can break 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.

Vi. several frameworks forAjax

We currently employ a more Ajax framework with Ajax . dll, Ajax pro.dll,magic Ajax . dll and Microsoft's Atlas framework. The two frameworks of Ajax . dll and Ajax Pro.dll are not very different, and magic Ajax . dll is just a bit more encapsulated. For example, it can return directly to the dataset dataset, as we have said earlier, Ajax Returns a string, and the magic Ajax just encapsulates 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 magic Ajax to handle, the operation is simple, add magic After Ajax , the list control to be updated is placed within the Magic Ajax Control, and the time to define the update interval in pageload is OK, and the principle and magic of Atlas Ajax almost. 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 it is to create our own XMLHttpRequest object , which is more flexible than the previous frameworks. In addition, here also mention the aspnet2.0 of the asynchronous callback interface, which, like Ajax can also implement a partial non-flush, but its implementation is actually based on the XMLHttpRequest object The , but also only support IE, of course, this is a Microsoft competitive strategy.

Vii. A simple example ofAjax

The function of the sample implementation is that when a user selects a province's name in a drop-down list box on a Web page, the provincial provincial name is displayed on the page, and the page is not refreshed. The name of the capital will be transferred from the server to the browser. This example contains three parts (the server is a PHP program)

1. HTML page with drop-down list box and location to display the name of the provincial capital

2. JavaScript program, implement send request and processing response.

3, the server side of the PHP program, to accept the browser request, to the browser to send the results data.

(client) HTML page:

 
  <strong>ajax</strong> Simple Application

Please select a province (autonomous region)

(server side) PHP program

 
  ' Hefei ', ' fj ' and ' Fuzhou ', ' gs ' = ' Lanzhou ', ' gx ' = ' nanning ', ' gd ' and ' Guangzhou ', ' gz ' and ' Guiyang ', ' hn ' = ' Haikou ', ' hb ' = ' Shijiazhuang ', ' hh ' = > ' Zhengzhou ', ' hlg ' = ' harbin ', ' if (Empty ($_get[' prov ') ') {echo iconv ("UTF-8", "UTF-8", ' You have not selected province ');//NOTE: Your PHP file is using GB2312 encoding Save, that Iconv ('GB2312', ' UTF-8 ', ' you have not selected province (autonomous Region)'); //Note: Your PHP file is saved with the GB2312 encoding, that Iconv ('GB2312', ' UTF-8 ', ' the provincial capital of the selected province '): '. $city);  }?>
Run effect

How Ajax Works ">


The above describes how Ajax works, including aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

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