Getting Started with Ajax programming

Source: Internet
Author: User
Tags format object end header html page object model string version
Ajax| Program | design


First, the main reason to use Ajax



1, through the appropriate AJAX application to achieve a better user experience;



2, some of the previous server burden to the client, to facilitate the client idle processing capacity to deal with, reduce the burden of server and bandwidth, so as to save the ISP space and bandwidth rental costs.



Second, the reference



The earliest author of the concept of Ajax, Jesse James Garrett, thinks Ajax is the abbreviation 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 role in the same collaboration, it includes:



• Standardized rendering using XHTML and CSS;
• 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;



Ajax works by adding a middle tier between the user and the server, enabling the user to respond asynchronously to the server. Not all user requests are submitted to the server, such as data validation and processing, which are given to the Ajax engine itself, and the Ajax engine submits the request to the server only if it is determined that the new data needs to be read from the server.






Figure 2-1






Figure 2-2









  Iii. Overview



Although Garrent lists 7 Ajax components, it is personally believed that the so-called Ajax core is JavaScript, XMLHttpRequest, and Dom, and that if the data format is XML, it can be added with XML ( Ajax data returned from the server can be in XML format or in other formats, such as text.



In the old interaction, the user triggers an HTTP request to the server, the server processes it, returns a new HTHL page to the client, and every time the server processes a client-submitted request, the client can only wait, and even if it is only a small interaction, By simply getting a very simple piece of data from the server, you return a full HTML page, and the user wastes time and bandwidth each time to reread the entire page.



With Ajax, the user will quickly respond to a wait without a page overload (screen) from almost every operation it feels.



1, XMLHttpRequest



One of the biggest features of Ajax is the fact that you can transfer or read or write data to the server without refreshing the page (also known as no Refresh Update page), which is mainly thanks to the XMLHTTP component XMLHttpRequest object. This can be sent to the desktop application only with the server data level exchange, and do not refresh the interface every time without each time the data processing to the server to do, which is to reduce the burden of the server and accelerate the response speed, shorten the user waiting time.



The first applications xmlhttp Microsoft, IE (IE5), by allowing developers to extend their functionality within a Web page using XMLHTTP ActiveX components, developers can transfer data directly to or from the server without navigating from the current Web page. This feature is important because it helps to reduce the pain of stateless connections, and it also eliminates the need to download redundant HTML, thereby increasing the speed of the process. The response of Mozilla (Mozilla1.0 above and above NetScape7) is to create its own inherited XML proxy class: the XMLHttpRequest class. Konqueror (and Safari v1.2, also a khtml based browser) also supports XMLHttpRequest objects, and opera also supports v7.6x+ objects in later versions of XMLHttpRequest. For most cases, XMLHttpRequest objects are similar to XMLHTTP components, and methods and properties are similar, except that a small subset of properties are not supported.



Application of XMLHttpRequest:



· The application of XMLHttpRequest object in JS



var xmlhttp = new XMLHttpRequest ();



• The application of Microsoft's XMLHTTP component in JS



var xmlhttp = new ActiveXObject (microsoft.xmlhttp);
var xmlhttp = new ActiveXObject (msxml2.xmlhttp);
XMLHttpRequest Object method
/**
* Cross-browser XMLHttpRequest instantiation.
*/



if (typeof XMLHttpRequest = = ' undefined ') {
XMLHttpRequest = function () {
var msxmls = [' MSXML3 ', ' MSXML2 ', ' Microsoft ']
for (Var i=0 i < msxmls.length; i++) {
try {
Return to new ActiveXObject (msxmls[i]+ '. XMLHTTP ')
catch (e) {}
}
throw new Error ("No XML component installed!")
}
}
function Createxmlhttprequest () {
try {
Attempt to create it "the Mozilla Way"
if (window. XMLHttpRequest) {
return new XMLHttpRequest ();
}
Guess Not-now the IE Way
if (window. ActiveXObject) {
return new ActiveXObject (Getxmlprefix () + ". XmlHttp ");
}
}
catch (ex) {}
return false;
};



XMLHttpRequest Object method





Method Describe
Abort () Stop current request
getAllResponseHeaders () Return the complete headers as a string
getResponseHeader ("Headerlabel") To ask a single header label as a string
Open ("Method", "URL" [, asyncflag[, "UserName" [, "Password"]]) Set the target URL, method, and other parameters of pending requests
Send (content) Send Request
setRequestHeader ("label", "value") Set header and send along with request





XMLHttpRequest Object Properties





Property Describe
onReadyStateChange Event triggers for state changes
ReadyState Object State (integer):
0 = not initialized
1 = in read
2 = Read
3 = in interaction
4 = Complete
ResponseText The server process returns a text version of the data
Responsexml The XML Document object that the server process returns the data as a compatible DOM
Status Status code returned by the server, such as: 404 = "Found at end of file", 200 = "Success"
StatusText Status text information returned by the server





2. JavaScript



JavaScript is a programming language that is used heavily in browsers, and he has been degraded to a bad language (he does use it rather boring) to be used to show off gadgets and pranks or tedious forms of verification. But the fact is that he is a real programming language, has its own standards and is widely supported in various browsers.



3, DOM



Document Object Model.



A DOM is a set of APIs for use with HTML and XML files. It provides a structural representation of the file, allowing you to change the contents and visible objects. Its essence is to build a bridge between Web pages and Script or program language.



The properties, methods, and events that all Web developers can manipulate and create files are represented by objects (for example, the document represents the "file itself" image, the Table object represents the HTML table object, and so on). These objects can be used by most browsers in today's Script.



A Web page built with HTML or XHTML can also be viewed as a structured set of data that is blocked in the DOM (Document Object Model), which provides the support for reading and writing of the objects in the Web page.



4, XML



Extensible Markup Language (extensible Markup Language) has an open, extensible, self-describing language structure that has become the standard for data and document transmission on the web. It is a language used to describe data structures, just like his name. He makes it easier to define some structured data, and he can exchange data with other applications.



5, comprehensive



The Ajax engine mentioned by Jesse James Garrett is actually a more complex JavaScript application that handles user requests, reads and writes to servers, and changes DOM content.



The JavaScript Ajax engine reads the information and interactively rewrites the DOM, which enables the web to be seamlessly refactored, which is the way that we've been using JavaScript and DOM to change the content of the page, which we've always used in a wide variety of ways, but to make the page truly dynamic, Not only to internal interaction, but also to  from the outside, in the past, we are to allow users to enter data and through the DOM to change the content of the page, but now, XMLHttpRequest, we can not overload the page to read and write data on the server, so that the user's input to the minimum.



Xml-based network communication is not new, in fact, both Flash and Java applets have a good performance, now this rich interaction is also available on the Web page, based on standardized and widely supported and technology, and do not need Plug-ins or download small programs.



Ajax is a transformation of traditional Web applications. Previously, the server generated the HTML page every time and returned it to the client (browser). In most sites, at least 90% of the pages are the same, for example: structure, format, header, footer, advertising, etc., the difference is only a small part of the content, but each server will generate all the pages and then return to the client, which is a waste of the invisible, whether for the user's time, bandwidth, CPU consumption , or to the bandwidth and space of the ISP's high-priced lease. If you click on a page, only a few K or dozens of k may be insignificant, but like Sina to generate millions of pages a day large ISP, can be said to be a huge loss. Ajax can be the middle tier for both the client and the server, to handle the client's request, and send the request to the server, as needed, what to take, how much to take, there will be no redundancy and waste of data, reduce the total amount of data download, and update the page without overloading the entire content, Just update the part that needs to be updated, compared to the pure background processing and overloading of the way to shorten the user latency, but also to minimize the waste of resources, based on standardized and widely supported and technology, and do not require plug-ins or download small programs, so Ajax for users and ISPs are dual-profit.



Ajax separates the interface from the application in the Web (or the separation of the data from the presentation), whereas in the past there was no clear boundary between the separation of data and presentation, which was beneficial to the Division of labor and the reduction of Web application errors caused by non-technical changes to the page, increased efficiency, is also more applicable to the current release system. Can also put some of the previous server burden of work to the client, to facilitate the client idle processing capacity to deal with.



  Four, the application



The emergence of Ajax concept, opened the era of refreshing update page, and there is a substitute for traditional web development in the form (form) submitted to update the Web page trend, can be regarded as a milestone. But Ajax does not apply to all places, its scope is determined by its characteristics.



An example of an application is the AJAX application of cascading menus.



Our previous approach to cascading menus is this:



In order to avoid the overloaded pages that are caused by each operation on the menu, instead of using each call back to the background, all the data for the cascading menu is read out and written to the array, and then the rendering of the subset item is controlled by JavaScript according to the user's action, which solves the response speed, Do not overload the page and avoid sending requests frequently to the server. However, if the user does not operate the menu or only a part of the menu, the read data will become redundant data and waste the user's resources, especially in the context of complex menu structure, the large amount of data (such as the menu has many levels , every level of food and hundreds of projects), this abuse is more prominent.



If Ajax is applied in this case, the results will be improved:



When we initialize the page, we only read all the data from its first level and show that when a user operates one of the first-level menus, all data for the level Two submenu to which the current level of the project belongs is requested by Ajax to the back desk, and if you continue to request an item from the level two menu that is already rendered, And then to request all the data of all level three menus for the two-level menu item that you are working on, and so on ... In this way, take what you use, take as much as you can, there will be no data redundancy and waste, reduce the total number of data downloads, and update the page without overloading the entire content, only update the part that needs to be updated, relative to the background processing and overloading of the way to shorten the user waiting time, but also to minimize the waste of resources.



In addition, Ajax can also implement data aggregation because of its ability to invoke external data, such as the beta version of the online RSS reader that Microsoft has just released on March 15, and the benefits of open data and the development of some of its own applications, For example, using Amazon's data for some novel book Search applications.



In short, Ajax is suitable for Web applications that have more interaction, read data frequently, and classify data in a good way.



  V. Advantages of Ajax



1, reduce the burden on the server. Because the fundamental idea of Ajax is "on-demand data", it is most likely to reduce the burden on the server of redundant requests and echoes;



2, no Refresh update page, reduce user actual and psychological waiting time;



First of all, the "on-demand data" model reduces the actual amount of data read, playing a very figurative analogy, if the overloaded way from one end to the original point to the other end of the words, then Ajax is to a point of origin to reach another end point;






Figure 5-1






Figure 5-2



Second, even if you want to read the larger data, and do not have the same white screen as reload, because Ajax is sent with the XMLHTTP request to get the server response data, without reload the entire page in the case of using JavaScript Operation Dom Final update page, So in the process of reading the data, the user is not faced with a white screen, but the original page state (or can add a loading hint box to let the user understand the state of the data read), only after receiving all the data to update the corresponding part of the content, and this update is instantaneous, users almost feel. In short, users are very sensitive, they can feel your thoughtfulness to them, although not likely immediate results, but in the user's mind a little bit of accumulation of their dependence on the site.



3, a better user experience;



4, can also put some of the previous server burden of work to the client, to facilitate the client idle processing capacity to deal with, reduce the burden of server and bandwidth, save space and bandwidth rental costs;



5, Ajax because it can call external data;



6, based on standardized and widely supported and technology, and do not need Plug-ins or download small programs;



7, Ajax makes the Web interface and application separation (also can be said to be separated from the data and presentation);



8, for users and ISPs are double surplus.



  Vi. Problems with Ajax



1, some handheld devices (such as mobile phones, PDAs, etc.) are not good enough to support Ajax;



2, with JavaScript Ajax engine, JavaScript compatibility and debug is a headache;



3, Ajax no refresh overload, because the page changes do not refresh the overload so obvious, so it is easy to bring trouble to users-users are not clear whether the current data is new or have been updated; the existing solutions are: in the relevant location hints, data updates of the area design more obvious, the data updated to user prompts, etc.;



4, the streaming media support no flash, Java applet good;



  Vii. concluding remarks



Better AJAX applications require more client-side development and thinking about the current Web application concept, and a good user experience comes from the idea of thinking for all users, not just some kind of 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.