Ajax Boost (4) using XML in requests and responses (2)

Source: Internet
Author: User

----Preface
In Ajax applications, there are few reasons to use XML as a format for sending data, but there are many reasons why the server sends back XML to the client.
Reason: (1) The client sends a request with a 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 send requests using name/value pairs. Therefore, you may send a name like this: Name=jennifer. Simply add a ampersand (&) between successive name/value pairs, and you can put it 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. It is seldom necessary to use the extra structure provided by XML (and the additional overhead it brings).
In fact, all the reasons that need to send XML to the server can be grouped into the following two basic categories:
The server accepts only XML requests. In such cases, you have no choice. The fundamentals described in the previous article should have enabled you to master the tools necessary to send such requests.
You are invoking a remote API that accepts only XML or SOAP requests. This is actually a special case of the previous situation, but it is worth mentioning it separately. If you want to use an API from Google or Amazon in an asynchronous request, there are special considerations.
If the server uses string name=jennifer&job=president to answer 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 that consists of a name/value pair, the response is more difficult to interpret than 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 a response to enable the client to obtain and interpret the response in a standard way, at least when the response contains more than one value.


----Using XML:
Realizing that there is no standard way to make the server use name/value pairs to respond to clients, the reason for using XML is obvious. When sending data to a client, name/value pairs are a good choice because server and server-side languages can easily interpret name/value pairs, as well as using XML when returning data to a client. There are several ways to get the XML response from the server and use the more standard code to extract the data, which is used in the client.
Listing 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>



----to treat XML as plain text
The simplest choice for working with XML (at least in terms of learning new programming techniques) is to handle it in the same way as other pieces of text returned by the server. In other words, basically ignoring the data format and focusing only on the server's response.
In this case, you would use the ResponseText property of the Request object as if the server were sending you a non-XML response.

Listing 2. Handling XML as a normal server response

function Updatepage () {   if (request.readystate = = 4) {     if (request.status = =) {       var response = Request.res ponsetext;//response have the XML response from the server       alert (response);}}   



In this code snippet, Updatepage () is the callback method, and request is the XMLHttpRequest object. Eventually, you'll get an XML response that concatenates everything together, in the response variable.
The value of the manifest 3.response variable:
<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>

Here, you can use the JavaScript split function to split this data and get the name and value of the element through a basic string operation. Without a doubt, this is a frustrating process, ignoring the fact that you spend a lot of time reading about the contents of the DOM (Document Object Model) in previous installments. So, I want to emphasize that you should keep in mind that with responsetext, you can easily use and output XML responses from your server, but I won't show you too much code, and you should not choose this approach to get XML data when you can use the DOM, as you'll see here.
Although it is possible to treat the server's XML-formatted response as if it were any other text response, there is no good reason to do so. Use the DOM-friendly JavaScript API to manipulate XML. There's something better, JavaScript and XMLHttpRequest objects provide a property that perfectly gets the XML response of the server and gets it in the form of a DOM Document object.
Listing 4 shows an example. This code is similar to listing 2, but does not use the ResponseText property, and the callback function uses the Responsexml property. This property is available on XMLHttpRequest, which returns the response of the server in the form of a DOM document.
Listing 4. Use XML as XML
 

function Updatepage () {   if (request.readystate = = 4) {     if (request.status = =) {       var xmldoc = Request.respo nsexml;//work with xmldoc using the DOM}}   Now you have a DOM Document that you can handle like any other XML. For example, you might want to get all the show elements later, as shown in Listing 5. Listing 5. Get all Show Element function Updatepage () {   if (request.readystate = = 4) {     if (request.status = =) {       var xmldoc = r Equest.responsexml;       var showelements = Xmldoc.getelementsbytagname ("show");     }   } }



If you're familiar with DOM, starting here, it should look a bit familiar. You can easily manipulate the XML received from the server using all of the DOM methods you know.
Of course, you can also mix common JavaScript code. For example, you can traverse all the show elements, as shown in Listing 6.
Listing 6. Traverse all show elements

function Updatepage () {   if (request.readystate = = 4) {     if (request.status = =) {       var xmldoc = Request.respo Nsexml;       var showelements = Xmldoc.getelementsbytagname ("show");       for (var x=0; x<showelements.length; x + +) {         //We know the first child of show is title, and the second is rat ing         var title = Showelements[x].childnodes[0].value;         var rating = Showelements[x].childnodes[1].value;         Now does whatever you want with the show title and Ratings       }}}   



With this very simple code, you are dealing with XML responses as XML rather than plain text without formatting, and using a little DOM and simple JavaScript to handle server responses. More importantly, you use a standardized format of--xml instead of a comma-separated value or a vertical bar-delimited name/value pair. In other words, you use XML in the place that best suits it, avoiding the use of it in inappropriate places (for example, when sending requests to the server).


----Other alternative methods for interpreting XML
In addition to processing XML as unformatted text or using the DOM, there is a very popular choice that is important and worth mentioning. That's JSON (JavaScript Object Notation), which is a free-text format bound to JavaScript. In general, what you can do with JSON can be done with the DOM, and vice versa; choice depends primarily on preference, and of course, the right approach for a particular application. For now, you should stick with the DOM and familiarize yourself with the DOM as you receive the server's response.

Copyright notice: I feel like I'm doing a good job. I hope you can move your mouse and keyboard for me to order a praise or give me a comment, under the Grateful!_____________________________________________________ __ Welcome reprint, in the hope that you reprint at the same time, add the original address, thank you with

Ajax Boost (4) using XML in requests and responses (2)

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.