Getting Started with Ajax Programming



First, the main reason for using Ajax

1, Ajax applications through appropriate to achieve better user experience;

2, the burden of some of the previous work of the server to pass to the client, help the client idle processing power to handle and reduce the burden on servers and bandwidth to achieve the saving of space and bandwidth ISP rental cost.

Second, the reference

Ajax the earliest proponent of this concept that Jesse James Garrett: Ajax is short for Asynchronous JavaScript and XML.Ajax is not a new language or technology, it is actually several technologies combined in a certain way by a collaboration with a total play their respective roles, including:

* XHTML and CSS using standardized presentation;

• Use DOM dynamic display and interaction;

• Using XML and XSLT for data exchange and processing;

* Use XMLHttpRequest for asynchronous data reading;

* Finally, handle all the data binding and JavaScript;

Ajax works the equivalent of the user and the server added - a middle layer that allows users of the asynchronous operation and the server response.Not all user requests are submitted to the server, such as - some data validation and data processing to do so to their own Ajax engine, only identified the need to read the new data from the server and then on his behalf by the Ajax engine, submit a request to the server.






Figure 1






Figure 2

Third, an overview of

Although Garrent lists the composition of seven Ajax technology, but personally think that the core of the so-called Ajax only JavaScript, XMLHTTPRequest and DOM, as if the XML data format used in the case, it can also be combined with an XML (Ajax from the serverthe returned data can be XML, it can be text and other formats).

Interaction in the old way, by the user triggers an HTTP request to the server, the server processes it and then returns a new HTHL page to the client, when the server processes the request submitted by the client, the client can only be idle waiting forand even if only a small interaction, just from the server by a simple data must return a complete HTML page, the user each time a waste of time and bandwidth to re-read the entire page.

After the use of Ajax on the user from feeling almost all of the operations will not quickly respond to reload the page (white screen) and wait.

1, XMLHTTPRequest

Ajax is one of the greatest features of the server without refreshing the page will be able to transfer or read data (also known as the update without refreshing the page), this feature mainly due to XMLHTTP component XMLHTTPRequest object.This allows desktop applications to be made only with the exchange server for data level, instead of the interface do not have to refresh each time data processing time will be submitted to the server to do the work, so that to reduce the burden on the server and speed up theresponse speed and shorten the waiting time for users.

Microsoft XMLHTTP is the first application, IE (IE5 and above) by allowing developers to use within Web pages XMLHTTP ActiveX components expand their functionality, developers can not navigate from the current Web page to transfer data directly to the server or from serveraccess the data.This feature is important because it helps reduce the pain-free status of connections, it can eliminate the need for HTML Xiazairongyu to improve the speed of the process.Mozilla (Mozilla1.0 above and NetScape7 above) is to create a response to the succession of its own XML proxy class: XMLHttpRequest class.Konqueror (and Safari v1.2, is also a browser based on KHTML) also supports the XMLHttpRequest object, and Opera will also be in its future versions v7.6x + support XMLHttpRequest object.For the most part, XMLHttpRequest object and the XMLHTTP component is very similar to the methods and properties are similar, only a small part of the property is not supported.

XMLHttpRequest application:

· XMLHttpRequest object in JS Application

var xmlhttp = new XMLHttpRequest ();

* Microsoft's XMLHTTP component of the JS

var xmlhttp = new ActiveXObject (Microsoft.XMLHTTP);

var xmlhttp = new ActiveXObject (Msxml2.XMLHTTP);

XMLHttpRequest Object Methods

/ **

* Cross-browser XMLHttpRequest instantiation.

* /

if (typeof XMLHttpRequest == 'undefined') {

XMLHttpRequest = function () {

var msxmls = ['MSXML3', 'MSXML2', 'Microsoft']

for (var i = 0; i
try {

return 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 Methods

Method Description

abort () Stop the current request

getAllResponseHeaders () as a string back to ask the full headers

getResponseHeader ("headerLabel") as a string back to ask a single header label

open ("method", "URL" [, asyncFlag [, "userName" [, "password "]]]) pending request to set the target URL, method, and other parameters

send (content) to send the request

setRequestHeader ("label", "value") and set the header and sent with the request

XMLHttpRequest Object Properties

Property Description

onreadystatechange event triggers a state change

readyState Object status (integer):

0 = not initialized

1 = read in

2 = Read

3 = interaction

4 = complete

responseText server process returns the text version of the data

responseXML server processes the data returned in the XML DOM document object is compatible

status status code returned by the server, such as: 404 = "file found in the end," 200 = "success"

statusText status text returned by the server

2, JavaScript

JavaScript in the browser is a widely used programming language, that he had been relegated to a bad language (he does use more boring), to the often used to make some to show off the gadgets andfrivolous or mischievous form validation monotone.But the fact is, he is a real programming language, with their own standards and in a variety of browsers are widely supported.

3, DOM

Document Object Model.

DOM HTML and XML files is to use a set of API.It provides the structure of the document representation, which allows you to change the content and visible.Its essence is to create web pages or programming language to communicate with the Script of the bridge.

WEB developers of all operational and create the file properties, methods and events to object to show (for example, document on behalf of "the document itself," the right, like, table object represents the HTML form object, etc.).These objects can be today's most browsers to access the Script.

Construction of a use HTML or XHTML pages can be viewed as a set of structured data, which were sealed in DOM (Document Object Model) in, DOM provides a web page to read and write in support of each object.

4, XML

Extensible Markup Language (Extensible Markup Language) has an open, scalable, and can be self-describing language structure, it has become online data and document transmission standards.It is used to describe the data structure of a language, just as his name the same.He made some definition of structured data more easily, and can he and other applications through the exchange of data.

5, integrated

Jesse James Garrett referred to the Ajax engine, actually a more complex JavaScript applications, used to process user requests, read and write the contents of the server and change the DOM.

JavaScript, Ajax engine reads the information and interaction to rewrite the DOM, which makes seamless web can be reconstructed, that is, change the page after the page has been downloaded content, which we have been through the extensive use of JavaScript and the DOMmethod, but to make it really dynamic web pages, not only to the internal interaction, you also need access to data from the outside, in the past, we allow users to input data and to change the page content through the DOM, but now, XMLHTTPRequest, you can let usIn the case of not reload the page to read and write data on the server, allowing users to input to a minimum.

XML-based network communications are not new, in fact, FLASH and JAVA Applet have good performance, and now the rich can also be used on a web page interaction, and based on standardized and widely support and technology, and does not require plug-ins ordownload a small program.

Ajax is the traditional application of a change in WEB.Every time before the server generates HTML pages and returned to the client (browser).In most sites, many pages are the same at least 90%, such as: structure, format, page headers, footers, advertisements, the difference is only a small part of the contents, but each time the server will generate allpage back to the client, this invisible being is a waste, whether it is for the user's time, bandwidth, CPU consumption, or for the ISP's high bandwidth and space for rent.If you press one to count, only a few tens of K or K may not seem like much, but like SINA day millions of pages to generate a large ISP, it can be said to be a huge loss.And AJAX can for the client and server are in the middle layer, to handle the client's request and as needed to send a request to the server, what to take what, how much to withdraw, there will be no data redundancy and wasteto reduce the amount of data downloaded, and update all the content pages do not reload, just need to update that part of the update can be compared to the pure way of background processing and override the user waiting time shortened, but also to reduce the waste of resourcesto a minimum, standardized and widely-based support and technical, and does not require plug-ins or download a small program, so Ajax is for the user and the ISP's win-win.

Ajax in the WEB interface and application of separation (also can be said to separate data and presentation), whereas previously there is no clear boundary between the two, and the separation of data and presentation separation is beneficial division of labor, to reduce non-technical staff of the pagechanges caused by the WEB application errors, improve efficiency, and more applicable to the present distribution system.Can also put the burden of some of the previous work of the server to pass to the client, help the client idle processing power to deal with.

Fourth, the application

Ajax philosophy, the update without refreshing the page opened a prelude to the era, and web development to replace the traditional use of form (form) to update web page to submit a trend, can be regarded as a milestone.But Ajax is not applicable to all areas, its scope is determined by its characteristics.

As an application example is the cascading menu on the application of aspects of Ajax.

Our previous treatment of the cascading menu like this:

In order to avoid the operation of each of the menu to reload the page caused, not by way of background each call, but one will be all the cascading menu to read out all the data and write array, then use JavaScript to the user's actionscontrol its presentation of a subset of items, so that although the response rate to solve the operation, not to reload the page and avoid frequently send requests to a server problem, but the menu if the user does not operate or only part of the operation menu, thenpart of the data read will be a waste of redundant data and the user's resources, especially in the menu structure is complex, the case of large volumes of data (such as the menu has a lot of levels, each level there are hundreds of food items)Such abuse is even more prominent.

If the application of Ajax in this case, the results would have changed:

In the initial page when we read out its first-class all the data and display, the menu at the user level, one when the current through the Ajax request to the background level of the project belongs to all of the secondary sub-menudata, if we continue to request the menu has been rendered a second time, again after the request operation corresponding to the second menu item menu, all the data at all three levels, and so on ... ... so, what to take what, how much to withdraw, there will be no data redundancy and waste, reducing the total amount of data download, and update all the content pages do not reload, just update to that part needs to be updated, both relative to the background processingset out the way to shorten waiting time for users, but also to minimize the waste of resources.

In addition, Ajax can call the external data, data aggregation can also function (of course, have the appropriate license), such as Microsoft has just released in the March 15 online RSS readers BETA version; also facilitate a number of open data, developmentown some applications, such as using Amazon's data for some of the new Book Search application.

In short, Ajax interactions for more frequent reading of data, data classification good WEB application.

V., Ajax the advantage

1, to reduce the burden on the server.Because the underlying Ajax concept is "on-demand access of data," so the greatest possible reduction of redundancy in the shadow of the server request and response burden;

2 update without refresh the page to reduce the waiting time the user the actual and psychological;

First, the "on-demand access of data" mode reduces the amount of data actually read, make a very vivid example, if the method is overloaded to return from one end to another end point of origin and then, then Ajax is toone end anchored to another end;






Figure 5-1






Figure 5-2

Second, even relatively large to read the data, they do not appear as black and white, like the case of RELOAD, as Ajax is to use XMLHTTP to send a request by the server response data, without reloading the entire page in the case of operation with Javascript DOM finalupdate page, so the process of reading the data, the user is not faced by black and white, but the original page state (or you can add a message box LOADING allow users to understand the data read state), only when the receiverafter all the data to update the corresponding part of the content, and this update is also the moment, users hardly feel.In short the user is very sensitive, and they can feel you on their thoughtful, though not likely the immediate effect, but bit by bit in the user's mind the accumulation of their dependence on the site.

3, a better user experience;

4, can also bear some of the previous work of the server to pass to the client, help the client idle processing power to handle and reduce the burden on servers and bandwidth, saving space and bandwidth rental costs;

5, Ajax can call the external data;

6, based on standardized and widely support and technology, and does not require plug-ins or download a small program;

7, Ajax the WEB and application in the separation of the interface (it can be said of data and presentation separation);

8, for the user and the ISP is a win-win.

Six, Ajax problem

1, a number of handheld devices (such as mobile phones, PDA, etc.) is still not well supported by Ajax;

2, with the JavaScript for the Ajax engine, JavaScript compatibility and DeBug things are a headache;

3, Ajax's no refresh reload, refresh the page change is not overloaded so obvious, so easy to bring trouble to the user - the user data is now not clear new or have been updated; existing solutions are: prompt in the relevant location, data updates are designed to be more obvious areas, data updated to the user prompt, etc.;

4, support for streaming media is not FLASH, Java Applet good.