Ajax technology )-

Source: Internet
Author: User

Ajax internal communication document I. Main reasons for using Ajax
1. Better User experience through appropriate Ajax applications;
2. Transfer the previous server workload to the client, which facilitates the idle processing capability of the client to reduce the burden on the server and bandwidth, this saves ISP space and bandwidth rental costs.

Ii. References
Jesse James Garnett, the earliest author of the Ajax concept, believes that:
Ajax is short for Asynchronous JavaScript and XML.
Ajax is not a new language or technology. It is actually a combination of several technologies in a certain way to play their respective roles in the same collaboration, including
Use XHTML and CSS for standardized rendering;
Use dom for Dynamic Display and interaction;
Use XML and XSLT for data exchange and processing;
Use XMLHttpRequest for asynchronous data reading;
Finally, use JavaScript to bind and process all data;
The working principle of AJAX is equivalent to adding an intermediate layer between the user and the server, so that user operations and server responses are asynchronous.
Not all user requests are submitted to the server, for example, some data verification and data processing are handed over to the Ajax engine,
The Ajax engine submits requests to the server only when it is determined that new data needs to be read from the server.

Iii. Overview
Although garrent lists seven Ajax components, I personally think that the core of AJAX is JavaScript, XMLHttpRequest, and Dom,
If the data format is XML, you can add XML (the data returned by Ajax from the server can be XML or text or other formats ).
In the old interaction mode, the user triggers an HTTP request to the server. After the server processes the request, it returns a new hthl page to the client,
Each time the server processes a request submitted by the client, the client can only wait idle, even if it is only a small interaction,
You only need to get a simple piece of data from the server and return a complete HTML page. Each time, you have to waste time and bandwidth to re-read the entire page.
After Ajax is used, users feel that almost all operations will quickly respond to the waiting without page overloading (white screen.
1. XMLHttpRequest
One of the biggest features of AJAX is that it can transmit or read/write data to the server without refreshing the page (also known as refreshing the new page ),
This feature mainly benefits from the XMLHTTP component XMLHTTPRequest object. In this way, you can send a desktop application Program Exchange data with the server only,
Instead of refreshing the interface every time, you do not need to submit the data processing work to the server every time,
In this way, the server load is reduced, the response speed is accelerated, and the user waiting time is shortened.
Microsoft was the first to apply XMLHTTP. IE (ie5 or above) allowed developers to use the XMLHTTP ActiveX component to expand their functions on the web page,
Developers can directly transfer data to the server or retrieve data from the server without having to navigate the current web page.
This function is very important because it helps reduce the pain of stateless connections. It can also eliminate the need to download redundant HTML, thus improving the process speed.
Mozilla (mozilla1.0 or later and netscape7 or later) responds by creating its own inherited XML proxy class:
XMLHttpRequest class. Konqueror (similar to Safari v1.2 and khtml-based browsers) also supports XMLHttpRequest objects,
Opera will also support XMLHttpRequest objects in Versions later than v7.6x +. In most cases,
The XMLHTTPRequest object is similar to the XMLHTTP component and has similar methods and attributes, but a small part of attributes are not supported.

XMLHttpRequest application:

// Ie support
If (window. activexobject &&! Window. XMLHttpRequest ){
Window. XMLHttpRequest = function (){
Return new activexobject (navigator. useragent. tolowercase (). indexof ('msie 5 ')! =-1 )? 'Microsoft. xmlhttp': 'msxml2. xmlhttp ');
};
}
Text processing of data returned by Server Processes
GET requests
Example:

VaR Req = new XMLHttpRequest ();
If (req ){
Req. onreadystatechange = function (){
If (req. readystate = 4 & Req. Status = 200 ){
Alert (req. responsetext );
}
};
Req. Open ('get', 'pageurl.html ');
Req. Send (null );
}

POST requests
Example:

var Req = new XMLHttpRequest ();
If (req) {
req. onreadystatechange = function () {
If (req. readystate = 4 & req. status = 200) {
alert (req. responsetext);
}< BR >};
req. open ('post', 'scripturl. CGI ');
req. setRequestHeader ('content-type', 'application/X-WWW-form-urlencoded');
req. send ('var1 = data1 & var2 = data2 ');
}< br> XMLHTTPRequest object method description
abort () stop the current request
getAllResponseHeaders () return the complete headers as a string
getResponseHeader ("headerlabel") as a string to return a single header tag
open ("method", "url "[, asyncflag [, "username" [, "password"]) sets the target URL, method, and other parameters of the pending request
send (content) send the request (Param must be passed in this way, because the background cannot get the hidden Params)
setRequestHeader ("label", "value ") set the header and send it together with the request (the 'post' method is required)

XMLHTTPRequest object attribute description
Onreadystatechange event trigger (req. Open ('post', 'servlet ') or Req. Open ('post', 'servlet', true) during asynchronous processing ))
Readystate object status (integer ):
0 = not initialized
1 = reading
2 = read
3 = interaction in progress
4 = complete
The text version of the data returned by the responsetext server process
Responsexml: XML Document Object compatible with Dom returned by the server process
Subject returned by the responsebody server (in non-text format)
Data Streams returned by the responsestream Server
Status Code returned by the Status server, for example, 404 = "found at the end of the file", 200 = "successful"
Status text returned by the statustext Server

2. Javascript
Javascript is widely used in browsers. Programming Language , He used to be devalued as a bad language (he is really boring ),
It is often used for show-off gadgets, pranks, or monotonous form verification. But the fact is that he is a real programming language,
Has its own standards and is widely supported in a variety of browsers.
3. Dom
Document Object Model.
Dom is a set of APIS for HTML and XML files. It provides the structure of the file, allowing you to change the content and visible objects.
In essence, it is a bridge between web pages and scripts or programming languages.
All the attributes, methods, and events that web developers can operate and create files are displayed as objects. For example, document represents the object,
Table objects represent HTML table objects ). These objects can be used as scripts by most browsers today.
A webpage built with HTML or XHTML can also be seen as a group of structured data, which is blocked in the DOM (Document Object Model,
Dom supports reading and writing of objects in a webpage.
Function loadcnt (){
VaR Req = new XMLHttpRequest ();
If (req ){
Req. onreadystatechange = function (){
If (req. readystate = 4 & Req. Status = 200 ){
If (req. responsetext! =-1 ){
Nodes=req.responsexml.doc umentelement. childnodes;
Browse_cnt.innertext = nodes. Item (0). text;
Comment_cnt.innertext = nodes. Item (1). text;
Score_cnt.innertext = nodes. Item (2). text;
}
}
}
Req. Open ('post', '$ path/ajaxcntctrl ');
Req. setRequestHeader ('content-type', 'application/X-WWW-form-urlencoded ');
Req. Send ("photo_id =" + document. form1.photo _ id. value );
}
}
// Responsexml.doc umentelement. getattribute ('STAT') = 'OK'
// Responsexml.doc umentelement. getelementsbytagname ('title') [0]. firstchild. Data;
4. xml
The Extensible Markup Language (Extensible Markup Language) has an open, scalable, and self-descriptive language structure,
It has become the standard for online data and document transmission. It is a language used to describe the data structure, just like its name.
He makes it easier to define some structured data and can exchange data with other applications.
<! --? XML version = \ "1.0 \" encoding = \ "UTF-8 \"?>
<Photo_cnt>
<Browse_cnt> 6 </browse_cnt>
<Comment_cnt> 6 </comment_cnt>
<Score_cnt> 6 </score_cnt>
</Photo_cnt -->
5. Comprehensive
Jesse James Garret's Ajax engine is actually a complicated JavaScript Application used to process user requests,
Read/write server and modify Dom content.
The Ajax engine of JavaScript reads information and interactively overwrites the Dom, which enables the web page to be refactored,
That is, after the page has been downloaded, the page content is changed. This is a widely used method through JavaScript and Dom,
However, to make the web page truly dynamic, not only internal interaction, but also external data needs to be obtained. In the past,
We allow users to input data and Change Webpage content through DOM. But now, XMLHttpRequest,
This allows us to read and write data on the server without reloading the page, so that the user input is minimized.
XML-based network communication is not a new thing. In fact, flash and Java Applet both have a good performance. Now this rich interaction is available on the web page,
It is based on standardized and widely supported technologies, and does not require plug-ins or downloading applets.
Ajax is a transformation of traditional Web applications. Previously, the server generated HTML pages each time and returned them to the client (browser ).
In most websites, at least 90% of the pages are the same, such as the structure, format, header, footer, and advertisement,
The difference is only a small part of the content, but every time the server generates all the pages and returns them to the client, this is an invisible waste,
Whether it is for the user's time, bandwidth, CPU consumption, or for the ISP's high-priced bandwidth and space. If one page is used,
Only a few K or dozens of K may be insignificant, but for example, Sina's large ISP that generates millions of pages every day, it can be said that the loss is huge.
AJAX can process client requests as the middle layer of the client and server, and send requests to the server as needed,
Data redundancy and waste will not occur if data is used or used, reducing the total amount of data downloads,
In addition, you do not need to reload all the content when updating the page. You only need to update the part that needs to be updated. Compared with the pure background processing and reload method, the user wait time is shortened,
It also minimizes the waste of resources, based on standardized and widely supported and technology, and does not require plug-ins or downloading applets,
Therefore, Ajax is a double profit for users and ISPs.
Ajax separates web interfaces from applications (data and presentation). In the past, there were no clear boundaries between the two,
The separation of data and presentation is conducive to the division of labor and cooperation, reducing web application errors caused by non-technical staff's modification of pages, improving efficiency,
It is also more suitable for the current release system. You can also transfer the previous server workload to the client, which facilitates the idle processing capability of the client.

4. Application
the emergence of Ajax concepts opens the prelude to the non-refresh and Update page era, and replaces the use of Form in traditional web development) the submission method updates the web page trend.
This is a milestone. However, Ajax is not applicable in all places, and its applicability is determined by its features.
An Example of an application is an Ajax application on cascading menus.
previously, the cascade menu was processed as follows:
to avoid page overloading caused by each menu operation, the backend interface is not called every time,
instead, all the data in the cascade menu is read at a time and written into an array. Then, JavaScript is used to control the presentation of its subset projects based on user operations,
This solution solves the problem of operation response speed, does not reload pages, and avoids frequent requests sent to the server,
However, if you do not operate the menu or only operate a portion of the menu,
part of the read data becomes redundant data and user resources are wasted, especially when the menu structure is complex and the data volume is large
(for example, the menu has many levels and each level of food has hundreds of projects), this disadvantage is even more prominent.
If Ajax is applied in this case, the result will change:
when initializing the page, we only read all the data of the first level and display it, when a user operates one of the level-1 menus,
requests all data of the level-2 sub-menus of the current level-1 project to the background through Ajax, if you continue to request an item in the displayed level-2 menu,
request all data of the level-3 menu corresponding to the level-2 menu item, and so on ...... In this way, data can be retrieved as much as you use it.
there will be no data redundancy or waste, reducing the total amount of data downloads, in addition, you do not need to reload all the content when updating the page. You only need to update the part that needs to be updated.
compared with the background processing and reload method, the user wait time is shortened, it also minimizes the waste of resources.
In addition, AJAX can call external data or aggregate data (of course, corresponding authorization is required ),
for example, the beta version of online RSS reader, which was just released by Microsoft in March 15, can also facilitate some open data and develop some applications,
for example, some novel book search applications using Amazon data.
In short, Ajax is suitable for Web applications with high interactions, frequent data reading, and good data classification.

V. Ajax advantages
1. reduce the burden on the server. Because the fundamental idea of AJAX is to "retrieve data on demand", it is possible to minimize the burden on servers caused by redundant requests and sound shadows;
2. The page is refreshed to reduce the user's actual and psychological waiting time;
First, the "retrieve data on demand" mode reduces the actual amount of data read,
If the method of overloading is to return from one end point to the origin point and then to another end point, Ajax means to reach another end point based on one end point;

Second, even if you want to read large data, you do not need to use a white screen like Reload. Because Ajax uses XMLHTTP to send a request to obtain the server response data,
When the entire page is not re-loaded, JavaScript is used to operate the Dom to finally update the page. Therefore, when reading data,
The user is not facing a white screen, but the original page status (or you can add a loading prompt box to let the user know the status of Data Reading ),
The content of the corresponding part is updated only after all the data is received, and this update is instantaneous and almost invisible to users. In short, users are very sensitive,
They can feel that you are considerate to them. Although they are unlikely to achieve immediate results, they will accumulate their dependence on the website in the hearts of users.
3. Better User Experience;
4. You can also transfer the previous server workload to the client, which facilitates the idle processing capability of the client,
Reduces the burden on servers and bandwidth, and saves space and bandwidth rental costs;
5. Ajax can call external data;
6. It is based on standardized and widely supported technologies, and does not require plug-ins or downloading applets;
7. Ajax separates the web interface from the application (or data and presentation separation );
8. This is a double profit for users and ISPs.

6. Ajax Problems
1. Some handheld devices (such as mobile phones and PDAs) cannot support Ajax yet;
2. Javascript-based Ajax engines, JavaScript compatibility and debugging are a headache;
3. Ajax does not refresh any new loads, because the page changes are not as obvious as refreshing or reloading,
It is easy to cause problems to users-users are not sure whether the current data is new or updated. The existing solutions include:
The relevant location prompts, data update areas are designed to be obvious, and user prompts are given after the data is updated;
4. The support for streaming media is not as good as flash and Java Applet;

VII. Conclusion
For better Ajax applications, more client development and thinking about the current web application concept are required, and a good user experience is required,
It comes from the concept of thinking for users everywhere, not simply a technology.

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.