Implement data exchange in Ajax applications

Source: Internet
Author: User
Tags xml attribute

The only purpose of the core Ajax API (XMLHttpRequest) is to send HTTP requests and exchange data between Web browsers and servers. For JavaScript code running on the Web page, you can use XMLHttpRequest to submit this request parameter to a server script, such as a Servlet or JSP page. The called Servlet/JSP will send back a response, which contains the data that is generally used to update the user's viewing content without refreshing the entire page. This method has unique advantages in terms of performance and availability, because it will reduce network traffic and the use of Web UI is almost the same as that of desktop GUI.

However, developing such a user interface is not simple, because you must use JavaScript on the client, and use Java (or equivalent language) on the server to implement data exchange, verification, and processing. However, in many cases, considering the benefits that will be gained from this, it is worthwhile to build an Ajax-based interface with extra effort.

In this article, I will introduce a main method for data transmission between the Ajax client and the server, and compare the differences between the traditional Web application model and the Ajax model. In addition, we will discuss the techniques for processing data on the server and client.

First, you will learn how to use JavaScript to encode the parameters of the request object on the client. You can use the so-called URL encoding (the default encoding used by Web browsers) or include Request Parameters in the XML document. The server will process the request and return a response whose data must be encoded. This article will discuss JavaScript Object Notation (JSON) and XML, which are the main response data format options.

Most of the content in this article will mainly introduce the XML-related APIs commonly used in Ajax applications. On the client side, XML APIs have limited functions but are sufficient. In most cases, you can use XMLHttpRequest to complete all required operations. In addition, you can use JavaScript to analyze XML documents in a Web browser and serialize the DOM tree. On the server side, there are many APIs and frameworks that can be used to process XML documents. This article describes how to use a standard Java API for XML to implement basic tasks. This API supports XML mode, XPath, DOM, and many other standards.

Through this article, you can learn the best techniques and the latest API for data exchange in Ajax applications. The sample code involved is in the following three packages: util, model, and feed. Classes in the util package provide methods for XML analysis, mode-based verification, XPath-based query, DOM serialization, and JSON encoding. The sample data model contained in the model package can be used for initialization from the XML document and then converted to the JSON format. The model directory also contains a Schema example for XML verification. Classes in the feed package can be used to simulate data feeds. Ajax retrieves information every 5 seconds to refresh the Web page. This article explains how to terminate an unfinished Ajax request and delete the XMLHttpRequest object after it is used to avoid Memory leakage in the Web browser.

The web directory contains JSP and JavaScript examples. AjaxUtil. js contains practical functions for sending Ajax requests, terminating requests, and processing HTTP errors. This file also provides JavaScript utilities for XML and URL encoding, XML analysis, and DOM serialization. The ajaxCtrl. jsp file acts as an Ajax controller, receives every Ajax request, forwards parameters to the data model, or provides processing, and then returns an Ajax response. Other Web files are examples that demonstrate how to use this practical method.

Build a request on the client

The simplest way to send data to the Web server is to encode the request as a query string. The string can be appended to a URL or contained in the request body based on the HTTP method used. If you need to send a complex data structure, a better solution is to encode the information in the XML document. I will introduce these two methods in this section.

Encode the request parameters. When developing traditional Web applications, you do not need to worry about the encoding of form data because Web browsers automatically perform this operation when users submit data. However, in Ajax applications, you must encode the request parameters. JavaScript provides a very useful function, escape (), which replaces any characters that cannot be part of the URL with % HH (where HH is the hexadecimal code. For example, any blank character is replaced with % 20.

A practical function buildQueryString () is provided for downloading the sample code. This function can be used to connect the parameters retrieved from the array and separate the names and values of each parameter by means of =, and place & characters between each name-Value Pair:

Function buildQueryString (params ){
Var query = "";
For (var I = 0; I <params. length; I ++ ){
Query + = (I> 0? "&":"")
+ Escape (params [I]. name) + "="
+ Escape (params [I]. value );
}
Return query;
}


Assume that you want to encode the following parameters:

Var someParams = [
{Name: "name", value: "John Smith "},
{Name: "email", value: "john@company.com "},
{Name: "phone", value: "(123) 456 7890 "}
];

The buildQueryString (someParams) Call generates results that contain the following content:

Name = John % 20 Smith & email = john@company.com & phone = % 28123% 29% 20456%



If you want to use the GET method, the query must be appended to the URL? Character. When using POST, set the Content-Type title to application/x-www-form-urlencoded through setRequestHeader (), and pass the query string to send () of XMLHttpRequest () method to send the HTTP request to the server.

Create an XML document. Using strings to build elements through their properties and data is the easiest way to create an XML document using JavaScript. If this solution is used, a practical method is required to escape &, <,>, ", and characters:

Function escapeXML (content ){
If (content = undefined)
Return "";
If (! Content. length |! Content. charAt)
Content = new String (content );
Var result = "";
Var length = content. length;
For (var I = 0; I <length; I ++ ){
Var ch = content. charAt (I );
Switch (ch ){
Case &:
Result + = "&";
Break;
Case <:
Result + = "<";
Break;
Case>:
Result + = "> ";
Break;
Case ":
Result + = """;
Break;
Case \:
Result + = "& apos ;";
Break;
Default:
Result + = ch;
}
}
Return result;
}


To make the task simpler, you also need some other utility methods, such:

Function attribute (name, value ){
Return "" + name + "=" "+ escapeXML (value) + """;
}


The following example constructs an XML document from an array of objects with the following three attributes: symbol, shares, and paidPrice:

Function buildPortfolioDoc (stocks ){
Var xml =" ";
For (var I = 0; I <stocks. length; I ++ ){
Var stock = stocks [I];
Xml + =" Xml + = attribute ("shares", stock. shares );
Xml + = attribute ("paidPrice", stock. paidPrice );
Xml + = "";
}
Xml + =" ";
Return xml;
}


If you prefer to use DOM, you can use the API of the Web browser to analyze XML and serialize the DOM tree. With IE, you can use the new ActiveXObject ("Microsoft. XMLDOM") to create an empty document. Then, you can use the loadXML () or load () methods to analyze the XML from a string or URL. When IE is used, each node has an xml Attribute. You can use it to obtain the XML Representation of the node and all its subnodes. Therefore, you can analyze the XML string, modify the DOM tree, And serialize the DOM back to XML.

Firefox and Netscape allow you to use document. implementation. createDocument (...) to create an empty document. Then, you can use createElement (), createTextNode (), createCDATASection (), and other methods to create DOM nodes. The Mozilla Browser also provides two APIs named DOMParser and XMLSerializer. The DOMParser API contains the parseFromStream () and parseFromString () methods. The XMLSerializer class has the following methods for serializing the DOM tree: serializeToStream () and serializeToString ().

The following function analyzes an XML string and returns the DOM document:

Function parse (xml ){
Var dom;
Try {
Dom = new ActiveXObject ("Microsoft. XMLDOM ");
Dom. async = false;
Dom. loadXML (xml );
} Catch (error ){
Try {
Var parser = new DOMParser ();
Dom = parser. parseFromString (xml, "text/xml ");
Delete parser;
} Catch (error2 ){
If (debug)
Alert ("XML parsing is not supported .");
}
}
Return dom;
}


The second function serializes a DOM node and all its sub-nodes, and returns XML as a string:

Function serialize (dom ){
Var xml = dom. xml;
If (xml = undefined ){
Try {
Var serializer = new XMLSerializer ();
Xml = serializer. serializeToString (dom );
Delete serializer;
} Catch (error ){
If (debug)
Alert ("DOM serialization is not supported .");
}
}
Return xml;
}


You can also use XMLHttpRequest as an analysis program or a serialized program. After the server receives a response to the Ajax request, the response is automatically analyzed. You can access the text version and DOM tree by using the responseText and responseXML attributes of XMLHttpRequest. In addition, the DOM tree is automatically serialized when it is passed to the send () method.

 


Send a request. In previous articles, I introduced the XMLHttpRequest API and a practical function sendHttpRequest (). You can find it in the ajaxUtil. js file in the example that provides the download. This function has four parameters (HTTP method, URL, a parameter array, and a callback). You can create an XMLHttpReq

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.