User interaction operations (interaction) drive the Web site. It is important to understand how to process response information, especially when using new interactive operations such as AJAX. Kris Hadloc explains the nature of the AJAX request-response process. You should understand this content to better serve user interaction operations.
Requests and responses
The AJAX engine is divided into many aspects, each of which is very important. If the engine executes a transaction that sends a request and receives the response information, it has many methods to process the response information. Response Information is an important part of the processing process, because the user will eventually interact with the response information.
This article explains in detail how to handle AJAX response information, provide feedback to users, and update as needed. We start from the request readiness state, and then explain the status of the response information, callback) and analyze the response information. This article also explains other aspects of response information, such as loading messages, error processing, and displaying response information.
I have created an example for you to download. This example contains an object-oriented AJAX engine that you can use in any AJAX application. Before discussing the response information, I would like to point out how to build an AJAX engine and send requests. First, let's take a look at the AJAX engine code without the Response Information Processing Section ):
Document. write (""); Function Ajax () { This. toString = function () {return "Ajax ";} This. http = new HTTP (); This. makeRequest = function (_ method, _ url, _ callbackMethod) {This. request = (window. XMLHttpRequest )? New XMLHttpRequest (): new ActiveXObject ("MSXML2.XMLHTTP "); This. request. onreadystatechange = _ callbackMethod; This. request. open (_ method, _ url, true ); This. request. send (_ url ); } } |
To create this object and send a request, you only need to use the following two lines of code:
Var ajax = new Ajax (); Ajax. makeRequest ('get', 'xml/content. xml', onResponse ); |
The second line of code above reflects the request method you selected, the XML Path or the server-side script of the request, and the callback method you want to call when receiving the response information. Now you have some knowledge about the AJAX engine and how to send requests. Let's take a look at how to process requests.
Ready for Ready) Status
The ready status is handled by the callback method. When we make a request, the callback method has been set. In this example, onResponse is set as a callback method, which is used in this article to process all the analysis code operations. We will use the following code to check the AJAX object readiness status in the callback method:
Function onResponse () { If (ajax. checkReadyState ('body', 'loading... ', 'loading...') = "OK ") {// Here is the analysis code } } |
The code above shows that four parameters will be passed to the checkReadyState method. The first parameter is the load loading message we want to display. the ID of the message div and the other three parameters are custom loading messages corresponding to different States. The div used to load messages is the body name, which makes the content and loaded messages merged when new data is loaded. The following is the actual checkReadyState method. It processes the code we just discussed and displays it with the parameters passed to us in div. This method is also included in the sample AJAX engine.
This. checkReadyState = function (_ id, _ 1, _ 2, _ 3) { Switch (this. request. readyState) {Case 1: Document. getElementById (_ id). innerHTML = _ 1; Break; Case 2: Document. getElementById (_ id). innerHTML = _ 2; Break; Case 3: Document. getElementById (_ id). innerHTML = _ 3; Break; Case 4: Document. getElementById (_ id). innerHTML = ""; Return this. http. status (this. request. status ); } } |
The checkReadyState method is useful for providing Page Status feedback. The following table shows the detected values:
Value |
Status |
0 |
Uninitialized is not initialized) |
1 |
Loading) |
2 |
Loaded has been Loaded) |
3 |
Interactive interaction) |
4 |
Complete completed) |
You can add a custom message for each loading status-it can be a simple string or an image tag in string format, such as displaying an animated GIF ). The following is an example:
Var loader = ""; Ajax. checkReadyState ('body', loader, loader ); |
Not only does the checkReadyState method process the Request status, but the HTTP object contained in it also detects and returns the Request status.
Request status
The Request status of the AJAX object is the same as that of the requested file. The HTTP object contained in the AJAX file processes all HTTP status code definitions described by W3C and returns them to the request method. Status Code is divided into five parts:
· 1xx of information
· Successful 2xx
· Redirection 3xx
· Client error 4xx
· Server error 5xx
The first digit in the preceding figure indicates the status code of a certain category. For example, if 2xx is successful, it means that it contains all the status code. The first number of the HTTP object check status code and performs a Conversion Based on the code category. After a category is detected, the HTTP object sends it to the response method, which returns the status code as a string. This is the HTTP status method:
This. status = function (_ status) { Var s = _ status. toString (). split (""); Switch (s [0]) {Case "1 ": Return this. getInformationalStatus (_ status ); Break; Case "2 ": Return this. getSuccessfulStatus (_ status ); Break; Case "3 ": Return this. getRedirectionStatus (_ status ); Break; Case "4 ": Return this. getClientErrorStatus (_ status ); Break; Case "5 ": Return this. getServerErrorStatus (_ status ); Break; } } |
Status Code is processed by checking the first number of the Code. Once the code check is completed, the original status code is sent to an appropriate method, which sends a string form of status code to the onResponse method. Then we can display this message to the user. If any error occurs, she/he will know what happened. On the other hand, if the request is successful, the data is displayed.
ResponseText and ResponseXML
The content of the response information may be in different forms, such as XML, plain text, X) HTML or JavaScript Object symbol JSON ). We can use two different methods to handle different received data formats: responseText or responseXML. The responseText method is used in XML-based formats. It uses the response information as a string to return precise content. Both plain text, X) HTML and JSON use responseText. Using this method in plain text or HTML is simple:
If (ajax. checkReadyState ('body', 'loading... ', 'loading...') = "OK ") { Document. getElementById ('body'). innerHTML = ajax. request. responseText; } |
It's the simplest! Once the load response information is complete, we call the AJAX object, use responseText to retrieve its value, and add it to the page.
Processing JSON response information requires a little more skill than processing plain text or X) HTML. The following is an example of a JSON file:
{'Header': 'How to Handle the Ajax response ', 'Description': 'an in-depth explanation of how to handle the Ajax response .', 'Sourceurl': 'http: // www.krishadlock.com/clients/informit/AjaxResponse/AjaxResponse.zip '} |
The data is divided into two parts by a colon :): Tag Name and value. The additional data is separated by commas (,) and divided into new name/value pairs. Now we know what JSON looks like. Here is how we analyze it:
If (ajax. checkReadyState ('body', 'loading... ', 'loading...') = "OK ") { Eval ("var response = (" + ajax. request. responseText + ")"); Document. getElementById ('body'). innerHTML =""+ Response. header +" " + Response. description +"
" + "Download the source files "; } |
JSON data is first analyzed by JavaScript using a simple eval () process ). Once the data has been analyzed and the response information objects have been created, we can simply get their response information values by name.
ResponseText can not only add content to the page, but also be useful when debugging AJAX requests. For example, you may not be ready to analyze the data, because you do not know what the labels are, whether they are XML or JSON files. This requires a way to detect the analyzed data. Once you know all the tag names, all you need to do is write code.
ResponseXML is also quite simple to use. However, similar to the JSON format, XML requires data analysis. The first transaction we need to execute is to identify the root node in the XML response information.
Var response = ajax.request.responseXML.doc umentElement; |
Next, we get all the elements by name and get their values:
Var header = response. getElementsByTagName ('header') [0]. firstChild. data; Var description = response. getElementsByTagName ('description') [0]. firstChild. data; Var sourceUrl = response. getElementsByTagName ('sourceurl') [0]. firstChild. data; |
Finally, we display the response information in the corresponding div Tag:
Document. getElementById ('body'). innerHTML =""+ Header +" " + Description +"
" + "Download the source files "; |
JSON is faster than XML when JavaScript is used, because the analysis code required by JSON is much less than XML, which directly leads to a faster JSON speed when analyzing a large amount of data. JSON is not as good as XML Because XML is more supported and more server-side development options are supported. You can make a choice based on the environment and the purpose of the request.
AJAX response information is an important part of AJAX communication. You need to process a lot of information, including the ready status, error handling, and loading status, and finally display it. With this information, you can focus on the response information to provide more information.
(