Occasionally, Ajax developers will notice thatXAnd realize that it representsXML. XML is one of the most common data formats in programming.ProgramServer Response in can bring tangible benefits. In this article, you will see how the server sends XML in the request response.
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-XMLHttpRequest. This 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 assume that XMLHttpRequest objects use 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, and XMLHttpRequest also supports this usage. There is nothing that can block you from sending XML to the server. Before this seriesArticle, 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?
It is easy to take it for granted that AJAX applications and their use of XML: The name of this technology (Ajax) and its core object (XMLHttpRequest) all imply the use of XML, XML is also frequently 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 andHTTP
One of the worst possible situations for a technology is that it becomes so popular that it cannot change some of its basic content. XMLHttpRequest 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 wantsDoOnly for the clientCode(Usually Javascript in a webpage) provides an HTTP request sending method. That's all. Nothing else.
Therefore, it may be better to change XMLHttpRequest to a more accurate name, such as httprequest or simple 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. In the end, we have to use XMLHttpRequest, which requires developers to know the fact that its name is not real.
To some extent, one of the best backtracing methods for browsers that do not support XMLHttpRequest (especially on Windows) is to use Microsoft IFRAME objects. It does not sound like XML, HTTP, or request, does it? Of course, all these may be involved, but this clearly shows that the XMLHTTPRequest object is more about sending requests without reloading the page, rather than involving XML or even HTTP too much.
Request isHTTPRatherXML
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 to request a webpage from the server, something like a http://www.google.com or a http://www.headfirstlabs.com is entered. Even if you do not enter http: //, the browser will add this part in the address bar. The first part, namely http: //, 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 yesHTTP Those who are new to the Web may be surprised by URLs like https://intranet.nextel.com. HTTPS indicates secure HTTP, but uses an HTTP protocol that is more secure than normal 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 carried out through HTTP, the idea that XML is a transmission technology used behind XMLHttpRequest is unreasonable. 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, the XMLHTTPRequest object only uses common HTTP. Therefore, when someone says "Oh, XMLHttpRequest is used 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.
UseXML(True)
So far, I am talking about where Ajax isNoUse XML. But in AjaxXAnd XML in XMLHttpRequest still have 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.
XMLOption
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 plain text is faster than converting text into the following XML (using name = Jennifer-like name/value pairs ):
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.
From the client to the serverXML
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 = Larry Lastname = gullahorn Street = 9018 heatherhorn drive City = rowlett State = Texas Zipcode = 75080 |
If you use plain text to send the data to the server, you can useList1Code. Similar to the example used in the first article in this series. SeeReferences.
List1.Use the normal text sender name/Value Pair
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 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 ); } |
Name/Convert value pairsXML
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 in the address element, but the server requires data to be encapsulated in the profile element.
2. the XML from the client uses the zipcode element, and the server wants the zip code to be included in the zip-code element.
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 to serverXML
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 inList2.
List2.UseXMLSending name/Value Pair
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 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.List2To the POST method. In addition, XML is sent through the send () method, instead of appending the parameter 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, but text/XML or XML is used for normal text transmission. 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 call send () and pass 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.
SendXML: Good or bad?
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.
StructureXMLNot a simple task
First, we must realize that constructing XML is not simple for requests. For exampleList2As shown in, 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.
XMLNot adding anything for 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 using the same data sent with the previous name/value pairs (seeList1. 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.
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.
Http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro7.html