Ajax Learning Series 8: Using XML in requests and responses (2)

Source: Internet
Author: User
Tags ruby on rails

In the previous article in this series, you saw how the Ajax application
XML format the request sent to the server. I also learned why this is not a good idea in most cases. This article focuses on a good idea in most cases: Returning XML responses to the client.
I don't really like writing articles that tell you what you shouldn't do. 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 refer to the link in the references ), this article teaches you 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 to use XML as the format for sending data, but there are many reasons for the server to send XML back to the client. 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, 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:

1. The server only accepts 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.
2. 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. Therefore, retrieving the name attribute is only a small matter.

This situation does not lead us to another direction. If the server uses the string name = Jennifer & job = President to respond 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, the escape sequence % 20 is used to represent a space. The text "Live together, die alone" will use live % 20 together, % 20die % 20 alone is sent over 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. But what should I do if the server sends back the TV series lost, alias and six degrees for one time? Although you can select many methods to send this response using plain text (listing 1 provides some examples), there is no extremely simple method that does not require some processing by the client, there is no standardization method.

List 1. Server Response for rating (different versions)

Show = alias & Ratings = 6.5 | show = Lost & Ratings = 14.2 | show = six % 20 Degrees & Ratings = 9.1

Alias = 6.5 & lost = 14.2 & six % 20 degrees = 9.1

Alias | 6.5 | lost | 14.2 | six % 20degrees | 9.1

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. Above all of this, you can
It is processed as plain text and its value is obtained 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 understand the data in Listing 2.

List 2. Server Response for rating (XML format)

<Ratings>
<Show>
<Title> alias </title>
<Rating> 6.5 </rating>
</Show>
<Show>
<Title> lost </title>
<Rating> 14.2 </rating>
</Show>
<Show>
<Title> six degrees </title>
<Rating> 9.1 </rating>
</Show>
</Ratings>

In terms of the meaning of a specific semicolon or marker, the code in Listing 2 is not concealed.

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:

1. as plain text that happens to be formatted as XML
2. As an XML document, it is represented by a DOM Document Object.
Next, for example, suppose there is a simple XML response from the server. Listing 3 shows a list of program ratings that are the same as the content described above (in fact, it is the same XML as listing 2, which is again provided here for your convenience ). I will use this sample XML in this part of the discussion.

Listing 3. Example of rating in XML format

<Ratings>
<Show>
<Title> alias </title>
<Rating> 6.5 </rating>
</Show>
<Show>
<Title> lost </title>
<Rating> 14.2 </rating>
</Show>
<Show>
<Title> six degrees </title>
<Rating> 9.1 </rating>
</Show>
</Ratings>

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 need to use the responsetext attribute of the request object, just like when the server sends you a non-XML response (see Listing 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
Alert (response );
}
}
}

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 4 only shows the callback method in the Ajax client code. 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.

In this code snippet, updatepage () is the callback method, and request is the XMLHTTPRequest object. In the end, you will get an XML response that concatenates everything in the response variable. If this variable is output, you will get a result similar to listing 5. (Note that the code in listing 5 should normally be a continuous line of code. The multiline format is used for normal display .)

Listing 5. response variable value

<Ratings> <show> <title> alias </title> <rating> 6.5 </rating>
</Show> <title> lost </title> <rating> 14.2 </rating> </show> <show>
<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, as you can see in listing 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 the Javascript split function 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 that using responsetext can easily use and output Server XML responses, but I will not show you too much code. When Dom can be used, you should not select this method to obtain XML data, as shown below.

Use XML as XML

Although the server's XML response can be treated as any other text response, there is no good reason to do so. First, if you have been faithfully reading this series, you have learned how to use Dom, a javascript-friendly API, to manipulate XML. In addition, the JavaScript and XMLHttpRequest objects provide an attribute that can perfectly obtain the XML response of the server and obtain it in the form of a DOM Document Object.

Listing 6 shows an instance. This code is similar to listing 4, but does not use the responsetext attribute. The callback function uses the responsexml attribute. This attribute is available on XMLHttpRequest. It 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 DOM document that can be processed just like any other XML. For example, you may need to obtain all show elements later, as shown in listing 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 all show elements, as shown in listing 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 9 shows a simple PHP script. Assuming an asynchronous client sends a request, the script will output 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

<? PHP

// 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> ";

Mysql_close ($ conn );

?>

You should be able to output XML in a similar way using your preferred server language.

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. JSON (JavaScript Object Notation) 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.

Conclusion

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 about the special scenarios that you want to send XML (and the scenarios that need to receive 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.

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.