The basics of developing smart Web applications with Ajax

Source: Internet
Author: User
Tags format anonymous end functions object model variables socket knowledge base
A. What is Ajax?

This name represents the asynchronous javascript+xmlhttprequest and means that you can set up socket communication between browser-based JavaScript and the server. Ajax is not a new technology, but a combination of possibilities that have been successfully used in a number of successful technologies in modern browsers. All AJAX applications implement a "rich" ui--this is achieved through JavaScript manipulating the HTML Document Object model and through the XMLHttpRequest of accurate positioning data retrieval. A typical example Ajax application is Google Labs (http://labs.google.com) Google Maps and Google suggest. These applications monitor user input onsite and provide real-time page updates. Most importantly, these events do not need to refresh the page while the user navigates through the map or enters a lookup string.

In fact, the technologies that support these amazing applications have been on the way for some time, although they require sophisticated skills and the skills to use browsers. Some patented products offer similar capabilities-such as Macromedia Flash Plug-ins, Java applets, or. NET runtime-for some time to be practical. The idea of introducing a script component that can be called to a server into a browser already exists in IE 5.0. Firefox and other popular browsers also add to the Explorer Army and support XMLHttpRequest in a built-in object form. With the advent of cross-platform browsers, these technologies have been recognized and formally presented as Ajax in a company called Adaptive Path in March 2004.

In short, because of Google's support and the installation of a bit of available browser technology, and for a "better user experience", everyone is adding client technology to the Web application.

Two. The difference between Ajax and traditional applications

A traditional Web application model is actually a basic event--the user is forced to submit a form to achieve a page exchange. That is, the form submission and page transfer are not guaranteed: there is a worse scenario-users need to click again. This is very different from Ajax-—— data crosses the line rather than the full HTML page transmission. This data exchange is implemented through a specific browser object: XMLHttpRequest, and then by the appropriate logic to process the results of each data request, and the specific area of the page rather than the full page is updated. The result is faster speed, less congestion and better information transfer control.

The traditional "Click-refresh" Web application forces the user to interrupt the work process while waiting for the page to reload. By introducing Ajax technology, a client script can talk to the server asynchronously and the user can still keep the input data. In addition to being transparent to the user, such asynchrony means that the server can have more time to process requests.

Traditional Web applications have all the processing agents to the server and force the server to state management. Ajax allows for flexible partitioning of application logic and state management between customers and servers. This eliminates a "Click-refresh" dependency and provides better server scalability. When the state is stored on the client side, you do not have to cross the server to maintain the session or save/end state-its lifespan is defined by the client.

Three. ajax--Distributed MVC

Although Ajax applications rely on JavaScript to implement the description layer, the processing power and knowledge base still exist on the server. At this point, Ajax applications are heavily communicating with the Java server-data input/output Web services and Servlets. The difference between a Java EE application with an AJAX-based description layer and a standard Java EE application is, first, that MVC is distributed through lines. By using Ajax, views are local and models and controllers are distributed-which gives developers the flexibility to decide which parts are client-based. Specifically, the local view generates graphics by manipulating the HTML DOM, the controller locally processes user input and expands to the server's processing based on the developer's judgment--via HTTP requests (Web services, XML/RPC, or others) The remote part of the model is downloaded to meet the needs of the client to update the client page in real time, and the status is collected at the client.

In future Ajax articles, we will discuss each of these components in more depth and provide examples of how they are applied together. Now, let's not say much more, so we'll analyze a simple Ajax example in detail.

Four. Postal code check and check

We will create an HTML page that contains three input fields (Zip,city and state). We will guarantee that the fields on the page will be populated with the first matching status value as long as the user enters the first three digits of the ZIP code. Once the user has entered the number of all five-bit zip codes, we will immediately decide and populate the corresponding city. If the ZIP code is invalid (not found on the server's database), then we will set the boundary of the ZIP code to red. Such visual cues help the user and become a standard in modern browsers (as an example, when Firefox finds a matching keyword in an HTML page, it highlights the part that matches what you entered in the browser lookup field).

Let's start by creating a simple html:zip,city and state containing three input fields. Note that once a character is entered into the Postal Area Code field field, the Method zipchanged () is invoked. The JavaScript function zipchanged () (see below) calls the function updatestate () when the zip length is 3 o'clock, while the function up-datecity () is called when the zip length is 5 o'clock. and Updatecity () and updatestate () take most of the work agent to another function ask ().

Zip:<input id= "ZipCode" type= "text" maxlength= "5" onkeyup= "zipchanged ()"
Style= "Width:60"/>
City: <input id=, "City" disabled maxlength= "style="/"width:160"
State:<input id= "state" Disabled maxlength= "2" style= "width:30"/>
<script src= "Xmlhttp.js" > </script>
<script>
var zipfield = null;
function zipchanged () {
Zipfield = document.getElementById ("ZipCode")
var zip = Zipfield.value;
Zip.length = = 3?updatestate (Zip): zip.length = = 5?updatecity (Zip): "";
}
function Updatestate (Zip) {
var Statefield = document.getElementById ("state");
Ask ("resolvezip.jsp?lookuptype=state&zip=" +zip, Statefield, Zipfield);
}
function updatecity (Zip) {
var Cityfield = document.getElementById ("city");
Ask ("Resolvezip.jsp?") Lookuptype=city&zip= "+zip, Cityfield, Zipfield);
}
</script>

The function ask () communicates with the server and assigns a callback function to handle the server's response (see the following code). Later, we'll analyze the dual-featured resolvezip.jsp, which looks for city or state information based on the number of characters in the zip field. Importantly, ask () uses XMLHttpRequest with asynchronous features, so populating the state and city fields or shaded zip field boundaries can be achieved without slowing down the data entry. First, we call Request.open ()-It opens the socket channel with the server, uses an HTTP verb (GET or post) as the first argument and the URL of the data provider as the second argument. The last parameter of Request.open () is set to true-it indicates the asynchronous nature of the request. Note that the request has not been submitted yet. With the invocation of Request.send (), the commit is initiated-this can provide any necessary payload for post. When using asynchronous requests, we must use the Request.onreadystatechanged property to allocate the requested callback function. (If the request is synchronized, we should be able to process the result immediately after calling Request.send, but we can also block the user until the request is complete.) )

HttpRequest = function () {
var xmlhttp=null;
try {
XMLHTTP = new ActiveXObject ("Msxml2.xmlhttp");
} catch (_e) {
try {
XMLHTTP = new ActiveXObject ("Microsoft.XMLHTTP");
\ catch (_e) {}
}
if (!xmlhttp && typeof xmlhttprequest!= ' undefined ') {
try {
XMLHTTP = new XMLHttpRequest ();
catch (e) {
XMLHTTP = false;
}
}
return XMLHTTP;
}

function Ask (URL, Fieldtofill, Lookupfield) {
var http = new HttpRequest ();
Http.open ("Get", url, True);
Http.onreadystatechange = function () {handlehttpresponse (HTTP, Fieldtofill,lookupfield)};
Http.send (NULL);
}

function Handlehttpresponse (http, Fieldtofill, Lookupfield) {
if (http.readystate = = 4) {
result = Http.responsetext;
if (-1!= result.search ("null")) {
LookupField.style.borderColor = "Red";
Fieldtofill.value = "";
} else {
LookupField.style.borderColor = "";
Fieldtofill.value = result;
}
}
}


The HttpRequest () function used for Ask () (see above) is a constructor for an instance of a xmlhttprequest across browsers; we'll analyze it later. So far, notice how the call to Handleresponse () is wrapped with an anonymous function-this function is the functions () {Handlehttpresponse (Http,fieldtofill, Lookupfield)}.

The code for this function is created dynamically and is compiled every time we assign a value to the Http.onreadstatechange property. As a result, JavaScript creates a pointer to the context in which all variables can access the method-ask () that is ending. In this way, anonymous functions and Handleresponse () can be guaranteed to fully access the variables of all context hosts until the reference to the anonymous function is collected by the garbage collector. In other words, whenever our anonymous function is invoked, it can seamlessly refer to Request,fieldtofill and Lookupfield variables as if they were global. Also, each ask () call creates a separate copy of the environment, and at that point the variables are saved with the value at the end of the function.

Now, let's analyze the function handleresponse (). Since it can be activated in different states of request processing, the function ignores all cases-except for the processing of the request-which corresponds to the Request.readystate property equal to 4 ("Completed"). At this point, the function reads the response text of the server. Contrary to what its name implies, XMLHttpRequest input and output are not limited to XML format. In particular, our resolvezip.jsp (see Listing 1 in the source code) returns plain text. If the return value is "unknown", the function assumes that the postal code is invalid and that the lookup field (Zip) boundary color is set to red. Otherwise, the return value is used to populate the field state or city, and the zip boundary is given a default color.

Xmlhttprequest-Transfer Object

Let's return to our XMLHttpRequest implementation of the cross browser. The last list contains a HttpRequest () function-it is up to the IE5.0 and Mozilla 1.8/firefox. For simplicity, we only create a Microsoft XMLHttpRequest object, and if the creation fails, we assume it is firefox/mozilla.

The core of this function is xmlhttprequest-, which is a native browser object that facilitates communication between anything, including the HTTP protocol, to the server. It allows you to specify any HTTP verbs, headers, and payloads, and can work asynchronously or synchronously. There is no need to download or install any plug-ins-although in the case of IE, XMLHttpRequest is an ActiveX integrated into the interior of the browser. Thus, the "Run ActiveX control and Plugins" default IE permission should be just right for use.

Most importantly, XMLHttpRequest allows an RPC-style programmatic query to the server without any page refreshes. It implements this in a predictable, controllable way-providing full access to all the details of the HTTP protocol-including any custom format for headers and data. In future articles, we'll show you some other industry agreements-you can run over these transport protocols such as Web services and XML-RPC-which greatly simplify the development and maintenance of large-scale applications.


Five. Server-side logic

Finally, the server-side resolvezip.jsp is invoked from the function ask (see Listing 1 in the attached source code). This resolvezip.jsp is invoked in two separate sites that are distinguished by the length of the current postal area code (see Zipchanged () function). The request parameter Lookuptype value is either state or city. For simplicity, we will assume that two files State.properties and City.properties are located in the root directory of the C drive in the server. The resolvezip.jsp logic is responsible for returning the lookup value with the appropriate preloaded file.
Our AJAX-enabled pages are now ready.

Six. Remote scripting technology-an alternative approach

Some of the older Ajax implementations are based on so-called remote scripting techniques. The idea is that the user's behavior causes queries to the server through an iframe, and the server responds with JavaScript, which is executed as soon as the client is reached. This differs considerably from the XMLHttpRequest approach, where the server responds to data while the client interprets the data. The benefit of this solution is that it supports older browsers.

The HTML section based on the IFRAME example (see Listing 2 in the attached source code) is very similar to what we used in the XMLHttpRequest scenario, but this time we'll introduce another IFRAME element-controller:

Zip:<input id= "ZipCode" type= "text" maxlength= "5" onkeyup= "zipchanged ()"
Style= "width:60" size= "20"/"
City: <input id=, "City" disabled maxlength= "style=" width:160 "20"
State:<input id= "state" Disabled maxlength= "2" style= "width:30" size= "20"/>
<iframe id= "Controller" style= "visibility:hidden;width:0;height:0" > </iframe>

We keep calling zipchanged () once per keystroke, but this time, the function ask () called from Zipchanged () (see Listing 3 in the attached source code) is responsible for setting the SRC attribute of the IFRAME instead of calling a XMLHttpRequest:

function Ask (URL, Fieldtofill, Lookupfield) {
var controller = document.getElementById ("Controller");
controller.src= url+ "&field=" +fieldtofill.id+ "&zip=" +lookupfield.id;
}

The server-side logic is described by a rough resolvezip.jsp (see Listing 4 in the attached source code). It differs from its XMLHttpRequest counterpart-it returns JavaScript statements that set the global value of the Variable field lookup and city, and call the function response () from the execution context of the global window once it arrives in the browser.

The function response () is a modified version of Handleresponse ()-a function that is exempt from processing outstanding requests (see Listing 2 in the source code attached to this article).

Seven. Problems

For simplicity, let's "look down" at some of the important questions in our sample code:

1. Fact-xmlhttprequest object instances and callback function calls are not corrupted after being used-this can lead to a memory leak after each call. Properly written code should destroy or reuse these instances in the object pool. Also, the client must use the same object management technology as the server software.

2. In most cases, errors are often not effectively addressed. For example, a call to Request.open () in method Ask () might throw an exception that must be captured and processed, even if the JavaScript exception Auto capture feature is not set in the browser. The Handleresponse () function is another example. It must check for headers and ResponseText values for possible server-side and communication errors. In the event of an error, it must try to recover and/or report an error. Properly developed AJAX applications should avoid "submitting" loose data as much as possible, since there are often problems with line disconnection and other low-level communications-so these programs must build a strong and self recovery framework to support this.

3. The current server-side framework provides considerable functionality-they can be in harmony with a free Refresh method. For example, let's consider a custom server-side authentication problem for a specified period of time. In this case, we must intercept the security system response to the XMLHttpRequest call, display the login screen, and then issue the request again after the user is authenticated.

All of these problems are typical of any application code that works with low-level APIs, and all of these problems can be solved. The good news is that the techniques needed to solve these problems are very similar to most Java development technologies, such as Web services, custom tags, and xml/xslt. The only difference is that these technologies are now used in the following form for the client:

· Web Services-using simple communication standards such as SOAP/REST/RPC

• Custom Label for clients-pack rich client controls and integrate AJAX features

• Data Manipulation-xml-based and based on XSLT technology

Eight. Summary

Ajax methods can provide people with a rich Internet experience that is the same as desktop applications. However, we must use AJAX technology selectively, such as when you are still shopping online, you absolutely do not want to let your credit card in the background to quietly start payment. Will Ajax become an ongoing motivator? We certainly hope so. For the past five years we've been working on developing AJAX applications and proving that it's robust and effective. However, it requires a developer to be proficient in a wide range of technologies rather than those used in traditional "Click-refresh" Web applications.

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.