How AJAX returns XML data from the server side

Source: Internet
Author: User
Tags add object functions html page interface string version window

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.war installed 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 = = 200) {
502 502 ' votes '). InnerHTML = Req.responsetext;
} else {
Alert ("There was a problem retrieving 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 table below 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 = loaded 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" >

<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 method= "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>
<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/DWR to 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?

* Manage 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 Skills

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.



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.