Understanding Ajax, Part 1: Using XML in requests and responses

Source: Internet
Author: User
Tags object serialization ruby on rails ibm developerworks

Ajax client/server communication can be tricky

Document options

Print this page

Print this page

Level: Intermediate

Brett McLaughlin(Brett@newInstance.com), Writer, editor, o'reilly Media Inc.

December 21, 2006

InPrevious Article in this seriesYou can see how Ajax applications format requests sent to the server in XML format. I also learned why this is not a good idea in most cases. This article focuses onYes indeedA good idea is to return an XML response to the client.

Actually, I don't like to write something that mainly tells you.NoThe article. Most of the time, it would be a very stupid article. I want to explain something in the first half, and then explain in the second half how bad an idea is to use the technology you just learned. To a large extent, this is the case in the previous article (if you miss that article, please referReferencesThe article explains how to use XML as the request data format of Ajax applications.

I hope this article will make up for the time you spend learning XML requests. In Ajax applications, there are few reasons for using XML as the format for sending data,DirectionClientResendXML has many reasons. Therefore, the XML knowledge you learned in the previous article will ultimately reflect some value in this article.

The server (sometimes) cannot respond to too many requests

You need to understand before in-depth study of the technology for retrieving XML responses from the server, it is a good idea to make the server send XML to respond to the request (and this is different from the XML request sent by the client ).

The client sends a request by name/value

Recall the previous article and you will know that in most cases, the client does not need to use XML because they will use name/value pairs to send requests. Therefore, you may send a name like this:name=jennifer. Simply add an "and" symbol between consecutive name/value pairs (&) To put them together, just like this:name=jennifer&job=president. With simple text and these name-value pairs, the client can easily request multiple values from the server. The extra structure provided by XML (and the additional overhead) is rarely used ).

In fact, all the reasons for sending XML to the server can be classified into the following two basic categories:

  • ServerOnlyAccept XML requests.In this case, you have no choice. The basic knowledge introduced in the previous article should have given you the tools necessary to send such requests.
  • You are calling a Remote API that only accepts XML or SOAP requests.This is actually a special case of the previous case, but it is worth mentioning separately. If you want to use APIs from Google or Amazon in an asynchronous request, there are some special considerations. In the next article, I will introduce these considerations and provide examples of sending such requests to APIs.

The server cannot (in a standard way) Send name/value pairs

When you send a name/value pair, the Web browser sends a request, the platform responds to the request, and carries a server program, use it to convert the name/value pairs into data that can be easily processed by the server program. In fact, every server-side technology-from java servlet to PhP, to Perl, and Ruby on Rails-allows you to call multiple methods to obtain values by name. ThereforenameAttribute is only a small matter.

This situation does not lead us to another direction. If the server uses a stringname=jennifer&job=presidentResponding to an application, the client does not have any standardized and easy way to split each pair into names and values. You must manually parse the returned data. If the server returns a response consisting of name/value pairs, the explanation difficulty of the response is the same as that of using semicolons, vertical bars, or any other non-standard formatting characters.

Give me some space!

In most HTTP requests, escape sequences%20It is used to indicate a space. The text "Live together, die alone" WillLive%20Together,%20Die%20AloneIs sent through HTTP.

For you, this means that there is no simple way to use plain text in the response, so that the client can get and interpret the response in a standard way, this is the case when the response contains at least multiple values. If your server only needs to send the number 42 back, plain text is a good choice. However, if the server needs to send back the TV series at a timeLost, aliasAndSix degreesWhat should we do about the recent ratings? Although there are many ways to send this response using plain text (Listing 1Some examples are provided), but there is no extremely simple method that does not require the client to perform some processing, nor is there a standardized method.

List 1. Server Response for rating (different versions)




Although it is not difficult to find a way to split these response strings, the client will have to parse and split these strings Based on semicolons, equal signs, vertical bars, and symbols. This is not a way to compile robust code that allows other developers to easily understand and maintain.

Enter XML

Realize that there is no standard way to make the server use the name/value pair to respond to the client, the reason for using XML is obvious. When sending data to the client, the name/value pair is a good choice, because the server and the server language can easily interpret the name/value pair; the same is true for returning data to the client using XML. In the first several articles in this series, you have seen the use of Dom to parse XML. In subsequent articles, you can also see how JSON provides an alternative for parsing XML. You can process XML as plain text and obtain its value in this way. Therefore, there are several methods to obtain XML responses from the server, extract data using standard code, and use the data in the client.

XML is easy to understand. For example, most programmers can understandListing 2.

List 2. Server Response for rating (XML format)

  <title>Six Degrees</title>

In terms of the meaning of a specific semicolon or marker,Listing 2The code in does not have any concealment.

Back to Top

Receive XML from server

Because the focus of this series is on the Ajax application mode client, I will not go into details about how server programs can generate xml responses. But when your client receives XML, you need to understand some special considerations.

First, you can use two basic methods to process an XML response from the server:

  • As plain text that happens to be formatted as XML
  • As an XML documentDocumentObject Representation.

Next, for example, suppose there is a simple XML response from the server.Listing 3Shows the list of program ratings that are the same as those described above (in factListing 2The same XML is provided here only for your convenience ). I will use this sample XML in this part of the discussion.

Listing 3. Example of rating in XML format

  <title>Six Degrees</title>

Process XML as plain text

The simplest choice for processing XML (at least for learning new programming technologies) is to process it in the same way as processing other text fragments returned by the server. In other words, the data format is basically ignored, and only the server response is concerned.

In this case, you must useresponseTextAttribute, just like when the server sends you a non-XML response (seeListing 4).

Listing 4. processing XML as a common Server Response

function updatePage() {
  if (request.readyState == 4) {
    if (request.status == 200) {
      var response = request.responseText;

      // response has the XML response from the server

Previous review

To avoid the occurrence of a large number of repeated code, these subsequent articles in this series only provide the part of the Code related to the topic discussed. Therefore,Listing 4Only the callback method in the Ajax client code is displayed. If you are not clear about the location of this method in a larger asynchronous application environment, review the previous articles in this series that describe the basic knowledge of Ajax applications.ReferencesThe links to the previous articles are listed.

In this code snippet,updatePage()Is the callback method,requestYesXMLHttpRequestObject. In the end, you will get an XML response that concatenates all the elements inresponseVariable. If this variable is output, you will get a result similar to listing 5. (Note,Listing 5Under normal circumstances, the code in should be a continuous line of code. The multiline format is used for normal display .)

Listing 5. response variable value

<title>Six Degrees</title><rating>9.1</rating></show></ratings>

Here, the most important thing to note is that XML runs as a whole. In most cases, the server does not use spaces and carriage return to format the XML, but concatenates everything, just as youListing 5. Of course, your application does not care too much about spaces, so this is not a problem, but it does make it difficult to read the code.

Here, you can use JavaScriptsplitFunction to split the data and obtain the element name and value through basic string operations. There is no doubt that this is a headache. It ignores the fact that you have spent a lot of time reading the content related to Dom (Document Object Model) in previous articles. Therefore, I want to emphasize that you should keep in mind thatresponseTextYou can easily use and output the server's XML response, but I will not show you too much code. When you can use Dom, you should not choose this method to obtain XML data, here you will see this.

Use XML as XML

AlthoughYesThe server's XML response is treated as any other text response, but there is no good reason for doing so. First, if you have been faithfully reading this series, you have learned how to use Dom, a javascript-friendly API, to manipulate XML. There are also better things, JavaScript andXMLHttpRequestThe object provides an attribute that perfectly retrieves the XML response from the server and uses the DOMDocumentObject.

Listing 6An instance is provided. This Code correspondsListing 4Similar, but not usedresponseTextAttribute. The callback function usesresponseXMLAttribute. This property is stored inXMLHttpRequestIt returns the server response in the DOM document format.

Listing 6. Treat XML as XML

function updatePage() {
  if (request.readyState == 4) {
    if (request.status == 200) {
      var xmlDoc = request.responseXML;

      // work with xmlDoc using the DOM

Now you have a DOMDocumentAnd can process it like any other XML. For example, you may need to obtain allshowElements, suchListing 7.

Listing 7. Getting all show elements

function updatePage() {
  if (request.readyState == 4) {
    if (request.status == 200) {
      var xmlDoc = request.responseXML; var showElements = xmlDoc.getElementsByTagName("show"); }

If you are familiar with Dom, you should be familiar with Dom from here. You can use all the DOM methods you know to easily manipulate the XML received from the server.

Of course, you can also mix common JavaScript code. For example, you can traverse allshowElements, suchListing 8.

Listing 8. traverse all show elements

function updatePage() {
  if (request.readyState == 4) {
    if (request.status == 200) {
      var xmlDoc = request.responseXML;

      var showElements = xmlDoc.getElementsByTagName("show"); for (var x=0; x<showElements.length; x++) {
        // We know that the first child of show is title, and the second is rating
        var title = showElements[x].childNodes[0].value;
        var rating = showElements[x].childNodes[1].value;

        // Now do whatever you want with the show title and ratings
      } }

Through this simple code, you process the XML response as XML rather than plain text without format, and use a little Dom and simple JavaScript to process the server response. More importantly, you use the standardized format-XML, instead of comma-separated values or vertical name/value pairs. In other words, you use XML in the most suitable place, avoiding it in the unsuitable place (for example, when sending a request to the server ).

Server-side XML: A simple example

I don't talk too much about how to generate xml content on the server, but it is worth looking at a simple example. I didn't give too many comments, so that you can think about how to deal with such a scenario on your own.Listing 9A simple PHP script is displayed. If an asynchronous client sends a request, the script outputs XML to respond to the request.

This is a powerful (brute force) method. The PHP script actually generates XML output manually. You can find many toolkit and APIs for PHP and many other server-side languages that allow you to generate xml responses. Regardless of your situation, this will at least let you know what the server-side script that generates XML and responds to the request looks like.

Listing 9. php scripts that return XML


// Connect to a MySQL database
$conn = @mysql_connect("mysql.myhost.com", "username", "secret-password");
if (!conn)
  die("Error connecting to database: " . mysql_error());

if (!mysql_select_db("television", $conn))
  die("Error selecting TV database: " . mysql_error());

// Get ratings for all TV shows in database
$select = 'SELECT title, rating';
$from   = '  FROM ratings';
$queryResult = @mysql_query($select . $from);
if (!$queryResult)
  die("Error retrieving ratings for TV shows.');

// Let the client know we're sending back XML
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
echo "<ratings>";

while ($row = mysql_fetch_array($queryResult)) {
  $title = $row['title'];
  $rating = $row['rating'];

  echo "<show>
  echo "<title>" . $title . "</title>";
  echo "<rating>" . $rating . "</rating>";
  echo "</show>";

echo "</ratings>";



You should be able to output XML in a similar way using your preferred server language. There are many articles on IBM developerworks to help you understand how to generate XML documents using your favorite server language (for more information, seeReferences).

Back to Top

Other optional methods for interpreting XML

In addition to processing XML as a non-formatted text or using Dom, there is also a very popular option, which is worth mentioning. That isJSON(JavaScript Object Notation), which is a free text format bound to JavaScript. This article does not have enough space to describe JSON. It will be discussed in subsequent articles. As long as you mention XML and Ajax applications, you will probably hear someone talking about JSON, so now I will tell you what your partners are talking about.

In general, everything that can be done with JSON can be done with Dom, and vice versa. Selection mainly depends on preferences and, of course, the right method should also be selected for a specific application. For now, you should stick to Dom and be familiar with Dom when receiving server responses. I will take up several articles and spend a lot of time exploring JSON. Then you can use that technology in the next application at will. Please continue with this series: more about XML will be introduced in subsequent articles.

Back to Top


From the beginning of the previous article in this series, I have been talking about XML almost all the time, but for the contribution of XML in the Ajax application mode, I still touch on the surface. In the next article, you will learn more aboutHopeSpecial scenarios for sending XML (you can also see the scenarios for receiving XML ). Specifically, you will observe web services from the perspective of Ajax interaction-including private web services and APIs like Google.

In short, the most important task is to think about when XML makes sense for your applications. In many cases, if your application works well, XML is just another technical buzzword that makes your headache, you should restrain your impulse to try XML in your application.

If you are in such an environment: the data sent by the server to you is very limited, or you use a strange comma-separated, vertical line-separated format, XML may bring you real benefits. Consider processing or modifying your server-side components to make them return responses in a more standardized way-using XML-instead of using specialized formats that are less robust than XML.

The most important thing is to realize that the more you know about Ajax-related technologies, the more careful you are to make decisions. Writing those Web 2.0 applications is really interesting (in subsequent articles, you will return to the user interface to see what is cool here), but note that, make sure that you do not abuse these technologies on a web page that can work properly to show off to your friends. I'm sure you can write excellent applications. Then, read the next article to learn more about XML.



  • You can refer toOriginal ENGLISH.

  • Master Ajax Series: Read other articles in this series.
  • Developerworks Chinese website XML Zone: Visit the developerworks XML area to get a lot of technical articles and tips, tutorials, standards, and IBM redbooks.
  • Developerworks China website Web Development Area: Obtain resources about Web 2.0, Ajax, wikis, PHP, mashup, and other web projects.
  • Developerworks China site Open Source Area: Resources for open source code development and implementation.
  • "Processing cache with JSON"(Bakul L. Patel, developerworks, September November 2006): Learn to cache verification metadata on the client.
  • "Tip: Use Stax to write XML documents"(Berthold Daum, developerworks, February January 2004): Read this short technical article to learn how to create XML documents using a low-level, cursor-based Stax API.
  • "Servlets and XML: Made for each other"(Doug Tidwell, developerworks, February May 2000): read this article to learn how to use Java Servlet with XML and generate xml from the server.
  • "XML problem: Use the python module xml2sql and dtd2sql"(David Mertz, developerworks, June 2001): This demonstration article describes two popular XML-related modules provided by python, learning to generate SQL statements to create and populate a database.
  • "Ajax for Java developers: Build Dynamic Java applications"(Philip McCarthy, developerworks, October 2006): Let's take a look at server-side Ajax from a Java perspective.
  • "Ajax for Java developers: Java object serialization of AJAX"(Philip McCarthy, developerworks, September October 2005): a Java perspective on how to send objects over the network and interact with Ajax.
  • "Use ajax to call the soap web service. Part 1: Construct a web service client"(James Snell, developerworks, January 2006): an in-depth study of this advanced article about integrating Ajax with existing soap-based Web Services, describes how to use the Ajax design mode to implement a web browser-based soap web service.
  • Xml.com: One of the easiest-to-understand online resources. If you are not an experienced XML programmer, learn about XML from here!
  • World Wide Web ConsortiumDom Homepage: The starting point for accessing all Dom-related technologies.
  • The Dom Level 3 Core Specification: Defines the Core Document Object Model, from available types and attributes to Dom usage in various languages.
  • The ecmascript language Bindings for Dom: If you are a javascript programmer and want to use DOM in the code, you may be interested in the appendix defined in level 3 Document Object Model Core.
  • "Ajax: A New Approach to Web Applications"(Jesse James Garret,Adaptive PathFebruary 2005): Read this Ajax-a must-read article by all Ajax developers.
  • Developerworks technical activitiesAndNetwork Broadcast: Keep an eye on these software briefs for technical developers.
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.