Ajax Learning (4)-using XML in requests and responses (2)

Source: Internet
Author: User

---- Preface
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.
Reason: (1) the client sends a request by name/value pair (2) the server cannot (in a standard way) Send a name/value pair
In most cases, clients do not need to use XML because they 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:
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.
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.
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. 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.

---- Use 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. There are several methods to obtain XML responses from the server, extract data using standard code, and use the data in the client.
List 1. Server Response (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 as when the server sends you a non-XML response.

Listing 2. 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 );
}
}
}
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.
Listing 3. 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, 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.
Although the server's XML response can be treated as any other text response, there is no good reason to do so. Use the JavaScript-friendly APIs such as Dom 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 4 provides an instance. This code is similar to listing 2, 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 4. 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 5.
Listing 5. 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 6.
Listing 6. 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 ).

---- 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. 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.

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.