Introduction to Ajax--hands-on article

Source: Internet
Author: User
Tags add object end functions header object model string version
Ajax From Moztwwiki
This article is the JavaScript for Mozilla Developer Center: void (0); >ajax:getting started (HTTP://DEVELOPER.MOZILLA.O ...) of translation. The author of the original and the history of the compilation can be seen on its history page (HTTP://DEVELOPER.MOZILLA.O ... action=history).

This article describes JavaScript: void (0); >ajax the basics of related technologies and provide examples for you to use.




Javascript:void (0); " What's >ajax?



Javascript: void (0); >ajax (Asynchronous JavaScript and XML, asynchronous JavaScript, and XML technology) is a new word, but the connotation is two JavaScript features that have existed for some time. These two functions have been neglected in the past, in Gmail, Google suggest and Google Maps after the emergence of the fame world know.

These two JavaScript features are:

* Send a request to the server without reading the page again (request)
* Parse, use XML file



The first step-how to issue XMLHttpRequest



In order to send HTTP requirements to the server with JavaScript, you must first make the entity (instance) in the relevant category (class). Internet Explorer First provides the XMLHTTP category as an ActiveX object, while Mozilla, Safari, and other browsers then support the categories and attributes in this ActiveX object in the XMLHttpRequest category.

So, if you want to cross browser, you can write this:

if (window. XMLHttpRequest) {//Mozilla, Safari, ...
Http_request = new XMLHttpRequest ();
else if (window. ActiveXObject) {//IE
Http_request = new ActiveXObject ("Microsoft.XMLHTTP");
}

(Since this program is for illustration only, it is the simplest way to write it.) In the third step of this article, there is another kind of writing that we use more often. )

Some versions of Mozilla browsers have errors when the server returns data that does not contain an XML Mime-type file header (header). To avoid this problem, you can overwrite the file headers returned by the server in the following ways, so as not to return the text/xml.

Http_request = new XMLHttpRequest ();
Http_request.overridemimetype (' Text/xml ');

The next step is to determine how the server is going to return the data, at which point you can specify a JavaScript function name to process the return value by using the onReadyStateChange attribute, for example:

Http_request.onreadystatechange = nameofthefunction;

Note that the specified function name has no parentheses and no parameters. In addition to specifying a function name, you can also define a new handler using the Javascript instant definition function, as follows:

Http_request.onreadystatechange = function () {
Do something.
};

Once you have decided to process the request, you need to call the open () and send () method in the HTTP request category, as follows:

Http_request.open (' Get ', ' http://www.example.org/some.file ', true);
Http_request.send (NULL);

* The first parameter of the Open () is the HTTP request method, which is chosen from the Get, POST and head, and can be supported on your host. To follow the HTTP standard, remember that these methods are all uppercase, or some browsers (such as Firefox) may not be able to ignore you. A list of other methods that HTTP request can support refer to the http://www.w3.org/Protocol ....
* The second parameter is the destination URL. Based on security considerations, you cannot call a Web page other than the same domain. If the domain is different, the error of "Insufficient permissions, denial of Access" occurs when you call open (). Most of the mistakes that we make are the pages in the DOMAIN.TLD Web site that call Www.domain.tld, just a little bit of difference.
* The third parameter determines whether this request is not synchronized and, if set to TRUE, continues to execute the rest of the program even if the server has not yet returned the data, which is the JavaScript: void (0); The meaning of the first a represented in >ajax.

The parameters of Send () can be anything that you want to pass to the server when you send the request at POST, and the data is listed as a query string, for example:

Name=value&anothername=othervalue&so=on

However, if you want to send data by POST, you must first change the MIME form to the following:

Http_request.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded ');

Otherwise, the server will not be able to ignore the information you pass over.


Step Two – Process the data returned by the server



The function name that handles the return value must be provided when the request is outgoing.

Http_request.onreadystatechange = nameofthefunction;

So let's take a look at what this function should do. First, it must check the current state of the request: if the status value of 4 indicates that the server has returned all the information, it can begin parsing the resulting information.

if (http_request.readystate = = 4) {
All OK, continue to parse
} else {
It's not done yet.
}

ReadyState all possible values are as follows:

* 0 (not yet started)
* 1 (in read)
* 2 (Read)
* 3 (exchange of information)
* 4 (all completed)

(Data Source: MSDN (http://msdn.microsoft.com/...)

Next, check the HTTP status code returned by the server. All status codes are available on the Web site (Http://www.w3.org/Protocol ...). , but we're going to be in the state of OK.

if (Http_request.status = = 200) {
Everything is available
} else {
There seems to be a problem, maybe the server returned 404 (check this page) or 500 (internal error) or something
}

After checking the HTTP status code returned, it is up to you to decide what to do with the returned data. There are two ways to access data:

* http_request.responsetext– This will send back the worth of string
* http_request.responsexml– This will treat the return value as a XmlDocument object, and then use the JavaScript DOM correlation function to process


Step three-everything is ready-simple example



OK, then do a simple HTTP example, demo just the various techniques. This JavaScript will ask the server for an HTML file (test.html) with the words "i ' m a test.", and then list the contents of the file with alert ().


Style= "Cursor:pointer; Text-decoration:underline "
>
Make a request


In this example:

* First user presses "make a request"
* This will call the MakeRequest () function, also passed the parameter value test.html (that is, the name of the HTML file, placed in the same directory)
* The request is then issued and the dominance is handed over to the onreadystatechange-specified alertcontents () function
* Alertcontents () Check that the response is normal and then alert () lists the contents of the test.html

You can then test this example (Http://www.w3clubs.com/moz ..., or refer to the test file (Http://www.w3clubs.com/moz ...).


Step Fourth – Process XML response values



In the previous example, after receiving the HTTP return value we used the contents of the test.html file with the Reponsetext attribute of the object, and then try the method of Responsexml property.

First, we need to make a well-formed XML file so that we can take it later. This file name called Test.xml, the contents are as follows:

<--l version= "1.0"-->

I ' m a test.


In the program, we call the file with a place that only needs to be modified as follows:

...
>
...

Then in Alertcontents (), we have to take alert (http_request.responsetext); Change to this:

var xmldoc = Http_request.responsexml;
var root_node = xmldoc.getelementsbytagname (' root '). Item (0);
alert (root_node.firstChild.data);

This allows us to get the XmlDocument object that Responsexml returns, and then takes the XML file content in a DOM-related way. You can refer to Test.xml's original code (Http://www.w3clubs.com/moz ...). and the Modified test program (Http://www.w3clubs.com/moz ...).

For other DOM-related methods, refer to the Mozilla Dom (http://www.mozilla.org/doc) file. As Java EE developers, we often seem to be concerned about the "back-end mechanism (backend mechanics)." We often forget that the main success of Java EE is in Web applications, and many reasons make people like to use web development applications, but primarily because of their ease of deployment, they allow the site to have millions of users at the lowest possible cost. Unfortunately, over the last few years, we've spent too much time on the back end, but not enough to make our Web user interface responsive to the nature and responsiveness of our users.

This article describes a method, Ajax, that you can use to build a more dynamic and responsive Web application. The key to this approach is the combination of JavaScript, DHTML, and asynchronous communication with the server on the browser side. This article also demonstrates how easy it is to enable this method: An AJAX framework (DWR) is used to construct an application that communicates directly from the browser to the backend service. If used properly, this powerful force can make the application more natural and responsive, thereby enhancing the user's browsing experience.

The sample code used in this application has been packaged as a separate war file for download.

Brief introduction

The term Ajax is used to describe a set of techniques that enable browsers to provide a more natural browsing experience for users. Before Ajax, the Web site forced the user into the Submit/wait/display paradigm, and the user's actions were always synchronized with the server's "Think Time." Ajax provides the ability to communicate asynchronously with the server, freeing users from the request/response loop. With Ajax, you can use JavaScript and DHTML to update the UI immediately when the user clicks the button, and to send an asynchronous request to the server to perform an update or query the database. When the request returns, you can use JavaScript and CSS to update the UI appropriately instead of refreshing the entire page. Most importantly, the user doesn't even know that the browser is communicating with the server: The Web site appears to be responding instantly.

While the infrastructure required for Ajax has been on for some time, the true power of the recent asynchronous request has not been exploited. Being able to have a very responsive web site is really exciting because it ultimately allows developers and designers to create "desktop-style (desktop-like)" Usability using standard html/css/javascript stacks.

Typically, in Java EE, developers are too focused on the development of services and persistence layers that the usability of the user interface is lagging behind. In a typical Java EE development cycle, it is often heard that "we have no time to put the UI" or "cannot be implemented in HTML." However, the following Web site proves that these reasons are no longer tenable:

    • BackPack
    • Google suggest
    • Google Maps
    • Palmsphere

All of these Web sites tell us that Web applications do not have to rely entirely on the reload of the page from the server to render changes to the user. Everything seems to happen in an instant. In short, the benchmark is set even higher when it comes to the responsiveness of the user interface.

Defining Ajax

Adaptive Path Company Jesse James Garrett this definition of Ajax:

Ajax is not a technology. In fact, it is a combination of several booming technologies in a new and powerful way. Ajax contains:

    • Representation based on XHTML and CSS standards;
    • Use the Document Object Model for dynamic display and interaction;
    • Asynchronous communication with the server using XMLHttpRequest;
    • Use JavaScript to bind everything.

This is great, but why do you want to name it Ajax? In fact, the term Ajax was created by Jesse James Garrett, who said it was "shorthand for asynchronous JavaScript + XML."

How Ajax Works

The core of Ajax is the JavaScript object XMLHttpRequest. This object was first introduced in Internet Explorer 5, which is a technology that supports asynchronous requests. In short, XMLHttpRequest allows you to use JavaScript to make requests to the server and process the response without blocking the user.

When you create a Web site, performing a screen update on the client provides a lot of flexibility for the user. Here are the features you can do with Ajax:

    • Dynamically update the total number of items in a shopping cart without requiring the user to click Update and wait for the server to resend the entire page.
    • Improves the performance of the site by reducing the amount of data downloaded from the server. For example, on Amazon's shopping cart page, when the number of items in the basket is updated, the entire page is loaded, which must download 32K of data. If you use Ajax to calculate the new total, the server will only return the new total, so the required bandwidth is only 1%.
    • Eliminates page refreshes each time the user enters. For example, in Ajax, if a user clicks Next on a paging list, the server data refreshes the list instead of the entire page.
    • Edit the table data directly instead of requiring the user to navigate to the new page to edit the data. For Ajax, when a user clicks Edit, the static table can be refreshed to a table that is editable by the content. After the user clicks Done, an AJAX request can be made to update the server and refresh the table so that it contains static, read-only data.

Everything is possible! Hopefully it will inspire you to start developing your own AJAX based sites. Before we begin, however, let's introduce an existing Web site that follows the traditional submission/wait/re-display paradigm, and we'll discuss how Ajax can improve the user experience.

What are the scenarios that Ajax can be used for? --An example: MSN Money page

A few days ago, while browsing the MSN Money page, there was an article about real estate investment that aroused my curiosity. I decided to use the site's "Rate This article" (Evaluate this article) feature to encourage other users to spend a little time reading this article. After I clicked the vote button and waited a little while, the entire page was refreshed, and a beautiful picture of thanks appeared in the original voting question.

Ajax, in turn, can make the user's experience more enjoyable by providing a more responsive UI and eliminating the flicker of page refreshes. Currently, because you want to refresh the entire page, you need to send a large amount of data because you have to resend the entire page. If you use AJAX, the server can return a 500-byte message that contains a thank-you message instead of sending 26,813-byte messages to refresh the entire page. Even with the high-speed Internet, the difference between 26K and 1/2k is very large. It is also important to refresh only the section related to the vote, rather than refreshing the entire screen.

Let's use Ajax to implement our basic voting system.

RAW AJAX: Direct use of XMLHttpRequest

As noted above, the core of Ajax is the JavaScript object XMLHttpRequest. The following example article evaluates the system to take you to the bottom of Ajax basics:http://tearesolutions.com/ajax-demo/raw-ajax.html. Note: If you have Ajax-demo.warinstalled in the local WebLogic container, you can navigate to http://localhost:7001/ajax-demo/raw-ajax.html.

Browse the application, vote, and see how it works. After you are familiar with the application, read on to learn more about how it works.

First, you have some simple anchor points that are connected to a javascriptcastvote (rank) function.
function Castvote (rank) {  var url = '/ajax-demo/static-article-ranking.html ';  var callback = Processajaxresponse;  EXECUTEXHR (callback, URL);

This function creates a URL for the server resource you want to communicate with and calls the internal function EXECUTEXHR, providing a callback JavaScript function that is executed once the server response is available. Because I want it to run in a simple Apache environment, the cast vote URL is just a simple HTML page. In practice, the URL that is invoked will record the number of votes and dynamically render the response that contains the total number of votes.

The next step is to issue a XMLHttpRequest request:
function executexhr (callback, URL) {  //branch for native XMLHttpRequest object  if (window. XMLHttpRequest) {    req = new XMLHttpRequest ();    Req.onreadystatechange = callback;    Req.open ("Get", url, true);    Req.send (null);  } Branch for Ie/windows ActiveX version  else if (window. ActiveXObject) {    req = new ActiveXObject ("Microsoft.XMLHTTP");    if (req) {      req.onreadystatechange = callback;      Req.open ("Get", url, true);      Req.send ();}}  

As you can see, executing a xmlhttprequest is not simple, but intuitive. As usual, in the field of JavaScript, most of the work is spent on ensuring browser compatibility. In this case, you first need to determine whether XMLHttpRequest is available. If it is not available, you will most likely want to use Internet Explorer, which will use the provided ActiveX implementation.

The most critical part of the EXECUTEXHR () method is the two lines:

Req.onreadystatechange = Callback;req.open ("Get", url, True);

The first line defines the JavaScript callback function, and you want it to execute automatically once the response is ready, and the "true" flag specified in the Req.open () method indicates that you want to execute the request asynchronously.

Once the server has finished processing XMLHttpRequest and returns it to the browser, the callback method that is set by using Req.onreadystatechange assignment is automatically invoked.
function Processajaxresponse () {  //only if Req shows "loaded"  if (req.readystate = 4) {    //only if "OK"    if (Req.status =) {      502 502 ' votes '). InnerHTML = Req.responsetext;    } else {      alert ("There was a problem ret Rieving the XML data: "+      Req.statustext);    }  

The code is fairly concise and uses a few magic numbers, which makes it hard to see what's going on. To figure this out, the following table (quoted from http://developer.apple.com/internet/webcontent/xmlhttpreq.html ) enumerates the commonly used XMLHttpRequest object properties.

Property

Describe

onReadyStateChange

Event handlers for events that occur each time the state changes

ReadyState

Object state Value:

  • 0 = uninitialized (uninitialized)
  • 1 = loading (loading)
  • 2 = loading complete (loaded)
  • 3 = interaction (interactive)
  • 4 = complete (complete)

ResponseText

The string form of the data returned from the server process

Responsexml

DOM-compliant document data objects returned from the server process

Status

Numeric code returned from the server, such as 404 (not Found) or 200 (ready)

StatusText

String information for accompanying status codes

Now the Processvoteresponse () function begins to show its meaning. It first checks the overall state of the xmlhttprequest to ensure that it is completed (Readystatus = 4), and then asks for the status of the request based on the server's settings. If everything is ok (status = = 200), use the innerHTML property to override the contents of the DOM's "votes" node.

Now that you've seen how the XMLHttpRequest object works, let's use a framework designed to simplify the asynchronous communication between JavaScript and Java applications to abstract specific details.

Ajax:dwr Way

Following the same process as the article evaluation system, we will implement the same functionality using the direct Web Remoting (DWR) framework.

Assuming that the article and the voting results are stored in a database, an object/relational mapping technique is used to complete the extraction work. In order to be as simple as possible, we do not use a database for persistent storage. In addition, the web framework is not used to make the application as generic as possible. Instead, the application starts with a static HTML file that can be assumed to be dynamically rendered by the server. In addition to these simplifications, applications should use the spring framework to correlate everything so that you can easily see how to use Dwr in a "real" application.

You should now download the sample application and familiarize yourself with it. The application is compressed into a standard war file, so you can put it into any web container-no configuration required. Once the deployment is complete, you can navigate to http://localhost:7001/ajax_demo/dwr-ajax.html to run the program.

You can view the HTML source code and see how it works. The most impressive thing is that the code is so simple-all interactions with the server are hidden behind the JavaScript object ajaxsamplesvc. Even more surprisingly, the AJAXSAMPLESVC service is not written by hand but is automatically generated! Let's go ahead and see how this is done.

Introduction of DWR

As demonstrated in the "Raw Ajax" section, it is cumbersome to create asynchronous requests directly using XMLHttpRequest. Not only is the JavaScript code lengthy, but you must consider the work that the server needs to do to locate the AJAX request to the appropriate service and marshal the results to the browser.

The purpose of the design DWR is to handle all the information pipelines needed to install the Web page to the back-end service. It is a Java framework that can be easily inserted into a Web application so that JavaScript code can invoke services on the server. It even integrates directly with the spring framework, allowing users to expose beans directly to Web clients.

Dwr's real subtlety is that after the user has configured a service to be exposed to the client, it uses reflection to generate JavaScript objects so that Web pages can use them to access the service. The Web page then simply joins the generated JavaScript objects as if they were directly using the service; Dwr seamlessly handles all the trivial details about Ajax and request positioning.

Let's take a closer look at the sample code and figure out how it works.

Application Details: DWR analysis

The first thing to note about the application is that it is a standard Java application that uses a layered architecture (layered architecture) design pattern. Using DWR to expose some services through JavaScript does not affect your design.

Here is a simple Java service that we will use the DWR framework to expose directly to JavaScript code:

Package Com.tearesolutions.service;public interface Ajaxsamplesvc {   Article castvote (int rank);}

This is an example of a simplification to an almost impossible degree, in which only one article can be voted on. The service is managed by spring, and the bean name it uses is Ajaxsamplesvc, and its persistence requirements depend on Articledao. For more information, see Applicationcontext.xml.

In order to expose the service as a JavaScript object, you need to configure DWR and add dwr.xml files to the Web-inf directory:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE dwr Public "-//getahead limited//dtd Direct Web Remoting 0.4//en" "Http://www.getahead.ltd.uk/dwr/dwr.dtd" >& lt;dwr> <allow>  <create creator= "Spring" javascript= "ajaxsamplesvc" >   <param name= " Beanname "value=" Ajaxsamplesvc "/>  </create>  <convert converter=" Bean "match=" Com.tearesolutions.model.Article "/>  <exclude method=" toString "/> <exclude  " Setarticledao "/> </allow></dwr>

The Dwr.xml file tells Dwr which services are to be exposed directly to JavaScript code. Note that the open Spring bean ajaxsamplesvc has been requested. DWR will automatically find the Springapplicationcontext that is set by the application. To do this, you must use the standard servlet filter Contextloaderlistener to initialize the spring ApplicationContext.

DWR is set to a servlet, so add its definition to Web.xml:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Web-app Public "-//sun Microsystems, INC.//DTD Web Application 2.3//en" "Http://java.sun.com/dtd/web-app_2_3. DTD "><web-app> <display-name>ajax examples</display-name> <listener> <listener-class > Org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <servlet&  Gt <servlet-name>ajax_sample</servlet-name> <servlet-class> Com.tearesolutions.web.ajaxsampleservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>dwr-invoker</servlet-name> <display-name>dwr servlet</display-name> <description>direct Web remoter servlet</description> <servlet-class >uk.ltd.getahead.dwr.DWRServlet</servlet-class> <init-param> <param-name>debug</ Param-name> <param-value>true</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ajax_sample</servlet-name> < url-pattern>/ajax_sample</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name >dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping></ Web-app>

After you have done this, you can load the http://localhost:7001/ajax-demo/dwrto see which services are available. The results are as follows:

Figure 3. Available services

Click the ajaxsamplesvc link to see an example implementation of how to use the service directly within an HTML page. It contains two JavaScript files that perform most of the functions:
<script type= ' text/javascript '    src= '/ajax-demo/dwr/interface/ajaxsamplesvc.js ' ></script>< Script type= ' text/javascript '    src= '/ajax-demo/dwr/engine.js ' ></script>

Ajaxsamplesvc.js are dynamically generated:

function Ajaxsamplesvc () {}ajaxsamplesvc.castvote = function (callback, p0) {   Dwrengine._execute (callback, '/ Ajax-demo/dwr ',  ' ajaxsamplesvc ', ' castvote ', p0);

You can now refactor raw-ajax.html files by replacing all XMLHttpRequest code with JavaScript object ajaxsamplesvc. You can see the results of the changes in the dwr-ajax.html file, and the following are the new JavaScript functions:

function Castvote (rank) {  ajaxsamplesvc.castvote (processresponse, rank);} function ProcessResponse (data) {var votetext = "

For voting!

" + "

Current ranking: "+ data.voteaverage +" out of 5

" + "

Number of votes placed: " + data.numberofvotes +"

"; 502 502 ' votes '). InnerHTML = Votetext; }

Amazingly simple, isn't it? The article domain object returned by the Ajaxsamplesvc object is serialized as a JavaScript object, allowing methods such as numberofvotes () and Voteaverage () to be invoked above it. Use this data within the HTML code that is dynamically generated and inserted into the div element "votes".

Next work

In subsequent articles, I will continue with the topic of Ajax, which covers the following areas:

    • Ajax Best Practices

Like many technologies, Ajax is a double-edged sword. For some use cases, there is no need to use Ajax for their applications, which in turn is detrimental to usability. I'll introduce some patterns that aren't appropriate, highlight some of the negative aspects of Ajax, and show some of the mechanisms that help mitigate these negative aspects. For example, is Ajax the right solution for Netflix movie browsers ? Or, how do you prompt the user for some problems and click the button again?

    • Managing cross-Request status

When using AJAX, the original document DOM changes, and a large amount of page state information is stored in the client variable. When a user tracks a link to another page in the application, the status is lost. When users click the Back button as usual, the initial page in the cache is presented to them. This will make users feel very confused!

    • Debugging Tips

When you use JavaScript to do more work on the client, if things don't go as expected, you need some debugging tools to help you figure out what's wrong.

Conclusion

This article describes the AJAX approach and shows how to use it to create a dynamic and responsive Web application. By using the DWR framework, you can easily integrate Ajax into your site without worrying about all the actual plumbing work that must be done.

Special thanks to Joe Walker of Getahead IT consulting and his team for developing such a magical tool as DWR. Thank you for sharing it with the world!

Download

The application source code that is demonstrated in this article is available for download:ajax-demo.war(1.52 MB).

Resources

    • Http://www.getahead.ltd.uk/dwr--getahead IT consulting firm.
    • "ajax:a New approach to Web applications" written by Jesse James Garrett (Adaptive path,2005 year February).
    • "Dynamic HTML and xml:the xmlhttprequest Object" (Apple Developer Connection).

Original source

An Introduction to Ajax

http://dev2dev.bea.com/pub/a/2005/08/ajax_introduction.html

<

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.