Ajax and XML (1)

Source: Internet
Author: User
Tags form post

From: http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro7.html

Now, no meaningful programming can be performed without using XML. Whether you are looking at web designers turning to XHTML, web programmers using JavaScript, server programmers using deployment description files and data binding, or back-end developers studying XML-based databases, all are using this extensible markup language. Therefore, XML is considered to be one of the core technologies at the bottom of Ajax.

However, this view reflects that AJAX applications are represented by the name selected by their core object --XMLHttpRequestThis name is not very good because it does not reflect the actual technical situation. In other words, most people think that XML is the core component of Ajax, just because they take it for granted
XMLHttpRequestThe object uses XML at any time. But this is not the case. The first part of this article provides the reason. In fact, XML rarely appears in most Ajax applications.

XML is indeed applied in Ajax, andXMLHttpRequestThis method is also supported. There is nothing that can block you from sending XML to the server. In the previous articles in this series, we use common text and name/value parameters to send data, but XML is also a feasible format. This article describes how to do this. But most importantly, I will discussWhyXML can be used as the request format, and why in most casesNoUse it.

XML: Is it useless?

An easy mistake for Ajax applications and their use of XML: The name of this technology (Ajax) and its core object (XMLHttpRequest) Implies the use of XML, and XML is often heard when talking about Ajax applications. However, this is a big mistake. If you want to be confident in writing asynchronous applications, you mustYesThis idea is wrong, and it is best to knowWhy?Error.

XMLHttpRequest: Bad Name and HTTP

One of the worst possible situations for a technology is that it becomes so popular that it cannot change some of its basic content.XMLHttpRequestThis is exactly the case. It is the basic object used in Ajax applications. It sounds like it was designed to send XML requests through HTTP requests or send HTTP requests in some XML format. Regardless of the Object NameSounds likeLike what, in fact it wantsDoIt only provides an HTTP Request Method for client code (usually Javascript in Web pages. That's all. Nothing else.

Therefore, ifXMLHttpRequestA more accurate name may be better, for exampleHttpRequestOr simply
Request. But now thousands of people use Ajax in their applications, and we know it takes several years (if not a decade) most users use new browsers such as Internet Explorer 7.0 or Firefox 1.5. Therefore, such modifications are not feasible. Eventually we have to use
XMLHttpRequestThis requires developers to know the fact that their names are not real.

To a certain extentXMLHttpRequestOne of the best backtracking methods for browsers (especially on Windows) is to use Microsoft
IFRAMEObject. It does not sound like XML, HTTP, or request, does it? Of course, all of these may be involved, but this clearly illustrates one thing --
XMLHttpRequest
Objects are more about sending requests without re-loading pages, rather than involving XML or even HTTP too much.

The request is HTTP rather than XML.

Another common mistake is to think that XML is used behind the scenes-Frankly speaking, I think so too! However, your opinion shows that you are not familiar with this technology. When a user opens a browser and requests a webpage from the server
http://www.google.comOrhttp://www.headfirstlabs.comSuch a thing. Even if you do not enter
http://The browser will also add this part in the address bar. The first part, that ishttp://It is a very intuitive clue about how to communicate: HTTP through Hypertext Transfer protocol. When writing code on a webpage to communicate with the server, both Ajax, normal form post, and even hyperlinks are used to deal with HTTP.

Https: Still HTTP

Those who are new to the Web mayhttps://intranet.nextel.comThis URL is strange.httpsIt indicates a secure HTTP, but uses an HTTP protocol that is more secure than general Web requests. Therefore, even HTTPS is actually using HTTP, although some security layers are added to block those curious eyes.

Since all web communication between the browser and the server is performed through HTTP, XML is considered to beXMLHttpRequestThe idea of a certain transmission technology used behind the scenes is meaningless. Of course, in the HTTP requestMediumXML can be sent, but HTTP is a precisely defined protocol and cannot disappear in a short time. In addition to explicitly using XML in requests or sending responses using XML,XMLHttpRequestThe object only uses common HTTP. Therefore, when someone says "Oh, called
XMLHttpRequestIt is because when using XML behind the scenes, you 'd better laugh at it and patiently explain what HTTP is and tell them that although XML canPassHTTP transmission, but XML is a data format rather than a transmission protocol. Through this discussion, we can deepen our understanding of it.

Back to Top

Use XML (true)

So far, I am talking about where Ajax isNoUse XML. But in AjaxXAndXMLHttpRequestIn
XMLIt still has its practical significance. There are multiple options for using XML in Web applications. This section will discuss the basic options, and the remaining sections will discuss the details in depth.

XML options

There are two basic usage of XML in asynchronous applications:

  • Send requests from webpages to servers in XML format
  • Receive requests from the server in XML format on the webpage

The first method is to send a request in XML. You need to set the request format to XML. You can use the API to complete the request, connect the request to the text, and then send the result to the server. In this way, the main task is to construct a request in a way that complies with XML rules and can be understood by the server. Therefore, the key here is actually the XML format. After obtaining the data to be sent, you only need to wrap it in XML syntax. This article will discuss the usage of XML in Ajax Applications later.

The second method is to use XML to receive requests. You need to receive responses from the server and then extract data from the XML (likewise, you can use APIs or the brute force method ). In this case, the key lies in the data from the server, and you just need to extract the data from the XML for use. This is the topic of the next article in this series. We will discuss it in detail later.

Some advice

Before discussing the use of XML in detail, I would like to give you a piece of advice: XML is not a concise, fast, and space-saving format. In the subsequent sections and the next article in this series, we will see that using XML in the context does have some good reasons for the requests and responses (especially responses) of XML and common text) there are some advantages in comparison. However, compared with common text, XML usually occupies more space and is slower, because the labels and semantics required by XML must be added to the message.

If you want to write a program that is fast and looks like a desktop application, XML may not be the best choice. If you start with plain text and find that XML is really needed, you can use it. However, if you use XML from the very beginning, it will certainly reduce the responsiveness of the application. In most cases, sending common text is faster than converting text into the following XML (similar
name=jennifer):

<name>jennifer</name>

See where the XML processing time is added: Wrap the text into XML; send additional information (note that I do not contain any surrounding elements, XML headers, or any other content that may appear in the actual request); let the server Parse XML, generate a response, and wrap the response in XML, and send itBackWebpage; let the webpage parse the response and finally use it. Therefore, you need to know when to use XML. Do not initially think that it can accelerate the application in many cases; but it can enhance flexibility, which we will discuss now.

Back to Top

XML from client to server

Let's take a look at XML as the format for sending data from the client to the server. We will first discuss the technical implementation, and then spend some time analyzing when it is appropriate and not suitable for use.

Sending name/value pair

In the 90% web application you wrote, the name/value pairs will eventually be sent to the server. For example, if you enter the name and address in the webpage form, you may want the data to take the following form:

firstName=LarrylastName=Gullahornstreet=9018 Heatherhorn Drivecity=Rowlettstate=TexaszipCode=75080

If you use plain text to send the data to the server, you can use the code shown in Listing 1. Similar to the example used in the first article in this series. See references.

Listing 1. Using plain text to send name/value pairs

function callServer() {  // Get the city and state from the Web form  var firstName = document.getElementById("firstName").value;  var lastName = document.getElementById("lastName").value;  var street = document.getElementById("street").value;  var city = document.getElementById("city").value;  var state = document.getElementById("state").value;  var zipCode = document.getElementById("zipCode").value;  // Build the URL to connect to  var url = "/scripts/saveAddress.php?firstName=" + escape(firstName) +    "&lastName=" + escape(lastName) + "&street=" + escape(street) +    "&city=" + escape(city) + "&state=" + escape(state) +    "&zipCode=" + escape(zipCode);  // Open a connection to the server  xmlHttp.open("GET", url, true);  // Set up a function for the server to run when it's done  xmlHttp.onreadystatechange = confirmUpdate;  // Send the request  xmlHttp.send(null);}

Convert name/value pairs into XML

If you want to use XML as the data format, you must first find a basic XML format to store data. Obviously, name/value pairs can all be converted into XML elements, where names are used as element names and values are used as element content:

<firstName>Larry</firstName><lastName>Gullahorn</lastName><street>9018 Heatherhorn Drive</street><city>Rowlett</city><state>Texas</state><zipCode>75080</zipCode>

Of course, XML requires a root element.Document snippets(Part of the XML document) requires a closed element. Therefore, you may need to convert the preceding XML into the following format:

<address>  <firstName>Larry</firstName>  <lastName>Gullahorn</lastName>  <street>9018 Heatherhorn Drive</street>  <city>Rowlett</city>  <state>Texas</state>  <zipCode>75080</zipCode></address>

Now, you can basically create this structure on the Web Client and send it to the server.

Communication, verbal

Before transmitting XML over the network, ensure that the server and the script for sending data can accept XML. It seems redundant for many people to emphasize it now and takes it for granted. However, many new users often think that XML can be correctly received and interpreted as long as it is sent over the network.

In fact, two steps are required to ensure that the XML data sent can be correctly received:

  1. Make sure that the XML script sent to it can accept the XML data format.
  2. Ensure that the script recognizes the specific XML format and structure used to send data.

Both of these two aspects may require you to communicate with each other, and you must clearly inform the other party! Strictly speaking, if you really need to send XML data, most script authors will help you, so it is not difficult to find scripts that can accept XML. However, you still need to ensure that the format is what the script expects. For example, assume that the server accepts data in the following format:

<profile>  <firstName>Larry</firstName>  <lastName>Gullahorn</lastName>  <street>9018 Heatherhorn Drive</street>  <city>Rowlett</city>  <state>Texas</state>  <zip-code>75080</zip-code></profile>

It looks similar to the XML above. There are only two differences:

  1. XML from the client is encapsulated inaddressElement, but the server requires data to be encapsulated inprofileElement.
  2. XML from the client is usedzipCodeWhile the server wants the zip code to be placed inzip-codeElement.

On a large scale, these minor problems are only the difference between the server receiving and processing data, but the server will completely fail and display ambiguous error messages on the webpage (possibly to its users. Therefore, you must specify the desired format of the server and insert the data to be sent into that format. Then, only in this case will the real technical problem of sending XML data from the client to the server be involved.

Send XML to the server

When sending XML to the server, more code is used to get data and package it into XML, instead of actually transmitting data. In fact, as long as the XML string sent to the server is ready, the sending work is the same as the normal text, as shown in Listing 2.

Listing 2. Sending name/value pairs with XML

function callServer() {  // Get the city and state from the Web form  var firstName = document.getElementById("firstName").value;  var lastName = document.getElementById("lastName").value;  var street = document.getElementById("street").value;  var city = document.getElementById("city").value;  var state = document.getElementById("state").value;  var zipCode = document.getElementById("zipCode").value;  var xmlString = "<profile>" +    "  <firstName>" + escape(firstName) + "</firstName>" +    "  <lastName>" + escape(lastName) + "</lastName>" +    "  <street>" + escape(street) + "</street>" +    "  <city>" + escape(city) + "</city>" +    "  <state>" + escape(state) + "</state>" +    "  <zip-code>" + escape(zipCode) + "</zip-code>" +    "</profile>";  // Build the URL to connect to  var url = "/scripts/saveAddress.php";  // Open a connection to the server  xmlHttp.open("POST", url, true);  // Tell the server you're sending it XML  xmlHttp.setRequestHeader("Content-Type", "text/xml");  // Set up a function for the server to run when it's done  xmlHttp.onreadystatechange = confirmUpdate;  // Send the request  xmlHttp.send(xmlString);}

Most of the code is very simple. It is worth mentioning in a few places. First, the data in the request must be manually formatted as XML. After reading three articles about object types in the document, is it easy to discuss it? Although it is not allowed to use Dom to create XML documents in Javascript, DOM objects must be converted into text before they are sent to the network through get or POST requests. Therefore, it is easier to format data using regular string operations. Of course, errors and incorrect input may easily occur, so you must be very careful when writing the code for processing XML.

After the XML is created, the connection is opened in the same way as the sent text. It is best to use post requests for XML, because some browsers limit the length of the GET request string, while XML may be very long. We can see that get is changed to the POST method in Listing 2. In addition, XML uses
send()Instead of appending the parameters at the end of the request URL. These are all very subtle differences and can be easily modified.

However, you must write a new line of code:

xmlHttp.setRequestHeader("Content-Type", "text/xml");

It seems hard to understand. It only tells the server to send XML instead of common name/value pairs. In either case, the sent data is text,text/xmlOr XML is sent as plain text. If you use a name/value pair, the corresponding row should be:

xmlHttp.setRequestHeader("Content-Type", "text/plain");

If you forget to tell the server that XML is sent, a problem occurs, so do not forget this step.

After this is done, the rest is to callsend()And passed in the XML string. The server will receive your XML request (assuming the preparation is ready), accept the XML, interpret it, and then return a response. In fact, there is only so much to do-XML requests only need to slightly modify the code.

Back to Top

Sending XML: good or not?

Before ending the XML request in XML response (and this article), let's take a moment to discuss how XML is used in the request. As mentioned above, XML is not the fastest method for transmission, but there are more factors to consider.

Constructing XML is not a simple task.

First, we must realize that constructing XML is not simple for requests. As shown in Listing 2, the data will soon be entangled with the XML semantics:

var xmlString = "<profile>" +  "  <firstName>" + escape(firstName) + "</firstName>" +  "  <lastName>" + escape(lastName) + "</lastName>" +  "  <street>" + escape(street) + "</street>" +  "  <city>" + escape(city) + "</city>" +  "  <state>" + escape(state) + "</state>" +  "  <zip-code>" + escape(zipCode) + "</zip-code>" +  "</profile>";

It seems not bad, but you must know that this is an XML segment with only six fields. Most Web forms developed have 10 to 15 fields. Although not all requests use Ajax, this situation should be considered. It takes at least as much time as the actual data to process angle brackets and tag names. This may make a small amount of input very large.

Another problem mentioned above is that you must create XML manually. Using Dom is not a good choice, because there is no easy way to convert a DOM object to a string sent in the request. Therefore, using string processing like this is the best method, but it is also the most difficult to maintain and the most difficult to understand for new developers. In this example, all the XML files are constructed in one row. If they are divided into multiple steps, they will be more chaotic.

XML does not add anything to the request

In addition to the complexity issue, using XML in requests is actually not very good (if any) compared to common text and name/value pairs ). Note that this article insists on sending the same data with the name/value pair (see Listing 1) in XML. I didn't mention any data that can use XML,NoThis is becauseNoNothing can be sent using XML instead of plain text.

In fact, this is the bottom line of XML and requests: it is not necessary to do so. In the next article in this series, we will see some things that are hard to achieve by using XML to implement common text on the server, but this is not the case for requests. Therefore, unlessOnlyAccept XML scripts (such scripts do exist) and use plain text in requests.

Back to Top

Conclusion

Through this article, you may now have a deeper understanding of XML in Ajax. You know that AJAX applications do not have to use XML, and XML is not a magic weapon in data transmission. I also know how difficult it is to send XML from a webpage to a server. More importantly, you know what needs to be done to ensure that the server can process and respond to requests: Make sure that the server script accepts XML and recognizes the format used to send data.

You should also know that XML is not necessarily a good data format for requests. In future articles, you will see that XML is advantageous in some cases, but in most requests, it will only reduce the speed and increase the complexity. Therefore, although I usually recommend that you apply the content you have learned in the article immediately, for this article, I suggest you think twice before applying the knowledge you have learned. XML requests have their own value in Ajax applications, but they are not as big as you think.

In the next article, we will discuss how the server uses XML to respond and how Web applications process these responses. Fortunately, the server is able to send XML back to Web applications, which is well justified. Therefore, the technical details in that article are more practical, currently, you only need to know why XML is not always the best choice-at least for sending requests. You can try to use XML as the request data format to implement some Web applications, and then switch back to common text to see which method is faster and simpler. Goodbye to the next article.

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.