[Learn Ajax in four days] The third day of the Ajax tutorial, the advanced request and response in Ajax

Source: Internet
Author: User

For many web developers, they only need to generate simple requests and receive simple responses. However, for developers who want to master Ajax, you must fully understand the HTTP status code, readiness status, and XMLHttpRequest object. In this article, Brett McLaughlin will introduce you to various status codes and show you how the browser processes them. This article also shows the rare HTTP requests used in Ajax.

In the previous article of this series, we will introduce the XMLHTTPRequest object in detail. It is the center of Ajax applications and is responsible for processing requests from server applications and scripts, and process the data returned from the server component. Because all Ajax applications use the XMLHTTPRequest object, you may want to familiarize yourself with this object so that AJAX can perform better.

In this article, I will focus on the three key parts of this request object based on the previous article:

· HTTP readiness
· HTTP status code
· Types of requests that can be generated

These three parts are all factors to consider when constructing a request, but there is little content to introduce these topics. However, if you want to know more about Ajax programming, you need to be familiar with the readiness status, status code, and request content. When an application encounters a problem -- this problem always exists -- if you can correctly understand the meaning of the ready state, how to generate a head request, or 400 status code, you can debug the problem within five minutes, instead of spending five hours in various setbacks and confusions.

Next, let's first look at the HTTP readiness status.

Learn more about HTTP readiness

You should remember that in the previous article, the XMLHTTPRequest object has an attribute named readystate. This attribute ensures that the server has completed a request. Generally, a callback function is used to read data from the server to update web forms or page content. Listing 1 provides a simple example (this is also an example in the previous article in this series-see references ).

XMLHttpRequest or XMLHTTP: Rose

Microsoft and Internet Explorer use an object named XMLHTTP instead of the XMLHTTPRequest object, whereas Mozilla, opera, Safari, and most non-Microsoft browsers use the latter. For simplicity, I simply call both objects XMLHttpRequest. This is consistent with what we see on the web and Microsoft's intention to use XMLHttpRequest as the request object in Internet Explorer 7.0. (For more information about this issue, see section 2nd .)

List 1. process the server response in the callback function

Function updatepage (){
If (request. readystate = 4 ){
If (request. Status = 200 ){
VaR response = request. responsetext. Split ("| ");
Document. getelementbyid ("order"). value = response [0];
Document. getelementbyid ("Address"). innerhtml =
Response [1]. Replace (// n/g, "<br/> ");
} Else
Alert ("status is" + request. status );
}
}

This is obviously the most common (and simplest) Use of readiness. As you can see from the number "4", there are several other readiness states (you have seen this list in the previous article-see references ):

· 0: the request has not been initialized (open () has not been called ()).
· 1: The request has been created but has not been sent (send () has not been called ()).
· 2: The request has been sent and is being processed (the content header can be obtained from the response ).
· 3: The request is being processed. Generally, some data in the response is available, but the server has not yet completed the response generation.
· 4: The response has been completed. You can obtain and use the server response.

If you want to understand more than just the basic knowledge of Ajax programming, you need to know not only these statuses, but also when they occur and how to use them. First, you need to learn which request status you may encounter in each ready state. Unfortunately, this is not intuitive and involves several special cases.

Secret ready status

The first readiness state is characterized by the readystate attribute 0 (readystate = 0), indicating that the State is not initialized. Once open () is called for the request object, this attribute is set to 1. Since you usually call open () immediately after a pair of requests are initialized, The readystate = 0 is rarely seen. In addition, the uninitialized readiness status is not really useful in the actual application.

However, to satisfy our interests, see the content in Listing 2, which shows how to obtain this readiness state when readystate is set to 0.

Listing 2. Getting the 0-ready status

Function getsalesdata (){
// Create a request object
Createrequest ();
Alert ("ready state is:" + request. readystate );

// Setup (initialize) the request
VaR url = "/boards/servlet/updateboardsales ";
Request. Open ("get", URL, true );
Request. onreadystatechange = updatepage;
Request. Send (null );
}

In this simple example, getsalesdata () is a function used by a Web page call to start a request (for example, when a button is clicked. Note that you must check the readiness status before calling open. Figure 1 shows the result of running the application.

Figure 1. readiness status 0

Obviously, this does not bring much benefit to you; you need to ensure that the open () function has not yet been called. In most cases of Ajax programming, the only use of this readiness state is to use the same XMLHTTPRequest object to generate multiple requests between multiple functions. In this (uncommon) case, you may want to ensure that the request object is not initialized (readystate = 0) before generating a new request ). This is actually to ensure that another function does not use this object at the same time.

View the readiness status of the request being processed

In addition to the 0 ready state, the request object also needs to go through several other ready states of the typical request and response in turn, and finally ends in the form of ready state 4. This is why you can see if (request. readystate = 4) This line of code ensures that the server has processed the request. Now, you can securely update the web page or perform operations based on the data returned from the server.

The process of viewing this status is very simple. If the ready status is 4, we must not only run the code in the callback function, but also output the ready status every time the callback function is called. Listing 3 provides an example to implement this function.

When 0 equals 4

When multiple JavaScript Functions use the same request object, you must check the ready state 0 to ensure that the request object is not in use. This mechanism may cause problems. Because readystate = 4 indicates a completed request, therefore, you often find that the ready request objects that are not currently in use are still set to 4-this is because the data returned from the server has already been used, however, no changes have been made since they are set to the ready state. A function abort () will reset the request object, but this function is not actually used for this purpose. If you must use multiple functions, it is best to create and use one function for each function, instead of sharing the same object among multiple functions.

 

Listing 3. view the readiness status

Function updatepage (){
// Output the current ready state
Alert ("updatepage () called with ready state of" + request. readystate );
}

If you are not sure how to run this function, you need to create a function and call this function on the web page, and send a request to the server component (for example, the function in Listing 2, or the example in section 1st and section 2nd in this series ). Make sure that the callback function is set to updatepage () when a request is created. To implement this setting, you can set the onreadystatechange attribute of the request object to updatepage ().

This code exactly shows the meaning of onreadystatechange-every time the request's readiness status changes, we call updatepage () and then we can see a warning. Figure 2 shows an example of calling this function. The ready state is 1.

Figure 2. Readiness 1

You can run this code by yourself. Put it into the web page, and then activate the event handler (click the button to switch the focus between domains by pressing the tab key, or trigger the request using any method set ). This callback function runs multiple times-the readiness status changes each time-you can see a warning for each readiness status. This is the best way to track all stages of a request.

Browser inconsistency

After a basic understanding of this process, try to access your page from several different browsers. You should notice how different browsers handle inconsistent readiness states. For example, in Firefox 1.5, you will see the following readiness status:

· 1
· 2
· 3
· 4

This is not surprising, because the status of each request is expressed here. However, if you use safari to access the same application, you should see-or not-something interesting. The status shown in Safari 2.0.1 is as follows:

· 2
· 3
· 4

Safari actually discards the first ready state, and there is no obvious reason why it should be done; however, this is the way safari works. This also illustrates an important issue: Although it is a good idea to ensure that the request status is 4 before using the data on the server, however, the code that depends on the readiness state of each transition period does get different results on different browsers.

For example, when opera 8.5 is used, the readiness state is worse:

· 3
· 4

Finally, Internet Explorer displays the following status:

· 1
· 2
· 3
· 4

If you encounter a request problem, this is the first place to identify the problem. The best way is to perform a test in Internet Explorer and Firefox -- you will see all the four statuses and check the status of each request.

Next, let's take a look at the response.

Response Data under a microscope

Once we understand the readiness status in the request process, next we can look at another aspect of the XMLHTTPRequest object -- responsetext attribute. Think back to the content we introduced in the previous article, you can know that this attribute is used to retrieve data from the server. Once the server completes processing the request, it can put any data required to respond to the request data into the request's responsetext. Then the callback function can use the data, as shown in Listing 1 and Listing 4.

Listing 4. Use the response returned by the server

 

Function updatepage (){
If (request. readystate = 4 ){
VaR newtotal = request. responsetext;
VaR totalsoldel = Document. getelementbyid ("Total-sold ");
VaR netprofitel = Document. getelementbyid ("Net-Profit ");
Replacetext (totalsoldel, newtotal );

/* Figure out the new net profit */
VaR boardcostel = Document. getelementbyid ("board-cost ");
VaR boardcost = gettext (boardcostel );
VaR mancostel = Document. getelementbyid ("man-cost ");
VaR mancost = gettext (mancostel );
VaR profitperboard = boardcost-mancost;
VaR netprofit = profitperboard * newtotal;

/* Update the net profit on the sales form */
Netprofit = math. Round (netprofit * 100)/100;
Replacetext (netprofitel, netprofit );
}

Listing 1 is quite simple; Listing 4 is a little complicated, but they must check the readiness status at the beginning and get the value of the responsetext attribute.

View request response text

Similar to the ready state, the value of the responsetext attribute also changes throughout the request lifecycle. To view this change, use the code shown in listing 5 to test the request response text and their readiness status.

Listing 5. Test the responsetext attribute

Function updatepage (){
// Output the current ready state
Alert ("updatepage () called with ready state of" + request. readystate +
"And a response text of '" + request. responsetext + "'");
}

Open the web application in the browser and activate your request. To better see the effect of this Code, use Firefox or Internet Explorer, because both browsers can report all possible readiness states during the request process. For example, in readiness 2, responsetext is not defined (see figure 3). If the Javascript console is enabled, you will see an error.

Figure 3. response text in readiness 2

However, in readiness 3, the server has put a value in the responsetext attribute, at least in this example (see figure 4 ).

Figure 4. response text in readiness 3

You will see that the response in the ready state is different in every script, every server, and even every browser. However, this is still very useful in application debugging.

Obtain security data

All documents and specifications emphasize that data can be safely used only when the ready state is 4 hours. Believe me, when the readiness status is 3, you can hardly find the situations where data cannot be obtained from the responsetext attribute. However, it is not a good idea to rely your logic on readiness 3 in an application-once you write code that relies on the full data of readiness 3, it is almost necessary to take charge of the incomplete data at that time.

A good practice is to provide some feedback to the user, indicating that a response will be generated soon when the user is in the ready state 3. Although alert () is used () A function like this is obviously not a good idea-using Ajax and then using a warning dialog box to block user errors-but you can update fields in the form or page when the readiness status changes. For example, for readiness 1, set the width of the Progress indicator to 25%, and for readiness 2, set the width of the Progress indicator to 50%, for readiness 3, set the width of the Progress indicator to 75%. When readiness is 4, set the width of the Progress indicator to 100% (complete ).

 

Of course, as you have seen, this method is very clever, but it relies on browsers. On opera, you will never see the first two readiness states, but on safari, there is no first (1 ). For this reason, I leave this code for practice, but it is not included in this article.

Now let's take a look at the status code.

In-depth understanding of HTTP status code

With the ready state and the response of the server you learned in Ajax programming technology, you can add another level of complexity to the Ajax application-this requires HTTP status code. These codes are nothing new to Ajax. Since the emergence of the Web, they already exist. You may have seen several status codes in a web browser:

· 401: unauthorized
· 403: forbidden
· 404: not found

You can find more status codes (For a complete list, see references ). To add another layer of control and response (and more robust error handling) Mechanisms for Ajax applications, You need to view the status code in the request and response as appropriate.

200: everything is normal

In many Ajax applications, you will see a callback function that checks the readiness status and continues to use the data returned from the server response, as shown in Listing 6.

Listing 6. Callback functions that ignore status code

Function updatepage (){
If (request. readystate = 4 ){
VaR response = request. responsetext. Split ("| ");
Document. getelementbyid ("order"). value = response [0];
Document. getelementbyid ("Address"). innerhtml =
Response [1]. Replace (// n/g, "<br/> ");
}
}

This proves to be a short-sighted and wrong method for Ajax programming. If the script requires authentication, but the request does not provide a valid certificate, the server will Return Error Code such as 403 or 401. However, because the server responds to the request, the ready state is set to 4 (even if the response is not what the request expects ). In the end, the user does not obtain valid data. When JavaScript tries to use non-existent server data, a serious error may occur.

It spent the minimum effort to ensure that the server not only completed a request, but also returned a "Everything is good" status code. This code is "200", which is reported through the status attribute of the XMLHTTPRequest object. To ensure that the server not only completes a request but also reports an OK status, add another check function to your callback function, as shown in listing 7.

Listing 7. Check the valid status code

Function updatepage (){
If (request. readystate = 4 ){
If (request. Status = 200 ){
VaR response = request. responsetext. Split ("| ");
Document. getelementbyid ("order"). value = response [0];
Document. getelementbyid ("Address"). innerhtml =
Response [1]. Replace (// n/g, "<br/> ");
} Else
Alert ("status is" + request. status );
}
}

By adding these lines of code, you can check whether there is a problem. The user will see a useful error message, not just a page consisting of a piece of out-of-band data, without any explanation.

Redirection and re-routing

Before going into the relevant error content, we need to discuss a problem that doesn't need to be concerned about when using Ajax-redirection. In the HTTP status code, this is the 300 series of status code, including:

· 301: permanent movement
· 302: Found (the request is redirected to another URL/uri)
· 305: Use a proxy (the request must use a proxy to access the requested resource)

Ajax programmers may not be too concerned about redirection issues due to two reasons:

· First, Ajax applications are usually written for a specific server-side script, Servlet, or application. For those components that you can't see and disappear, the Ajax programmer is not very clear. So sometimes you know that the resource has been moved (because you have moved it, or you have moved it by some means). Next, you need to modify the URL in the request without encountering such a result.
More importantly, Ajax applications and requests are encapsulated in the sandbox. This means that the domain of the web page that provides Ajax requests must be the domain that responds to these requests. Therefore, the web pages provided by ebay.com cannot generate an Ajax-style request for a script running on Amazon.com; ajax applications on ibm.com cannot send requests to Servlets running on netbeans.org.
· The result is that your request cannot be redirected to another server without a security error. In these cases, you will not get the status code at all. Generally, a javascript error is generated in the debugging console. Therefore, after fully considering the status code, you can completely ignore the issue of redirection code.

The result is that your request cannot be redirected to another server without a security error. In these cases, you will not get the status code at all. Generally, a javascript error is generated in the debugging console. Therefore, after fully considering the status code, you can completely ignore the issue of redirection code.

Error

Once you receive status code 200 and realize that the 300 series of status code can be ignored to a large extent, the only group of code to worry about is the 400 series code, this indicates different types of errors. Let's look back at listing 7, and note that only a few common error messages are output to the user during error handling. Although this is a step forward in the right direction, it is not very useful to tell users and programmers who are engaged in Application Development what is wrong.

First, we need to add support for pages that cannot be found. In fact, this should not happen in most product systems, but it is not uncommon when the test script location changes or the programmer inputs a wrong URL. If you can report 404 errors, You can provide more help to users and programmers who are suffering. For example, if a script on the server is deleted, we can use the code in listing 7, so that the user will see a non-descriptive error as shown in Figure 5.

Border conditions and difficulties

Now, some novice programmers may discuss what this is about. One thing you need to know is that less than 5% of Ajax requests require readiness code such as 2 and 3 and Status Code such as 403 (in fact, this ratio may be closer to 1% or even less ). These situations are very important, known as edge cases-they only happen in some very special circumstances, where they all encounter the most strange problems. Although these situations are not common, these boundary situations occupy 80% of the problems most users encounter!

 

For typical users, the fact that applications work normally for 100 times is often forgotten. However, once an error occurs, the application will be clearly remembered by them. If you can handle the Boundary Situation (or difficult situation) Well, you can provide a satisfactory return for users who access the site again.

Figure 5. common error handling

The user cannot determine whether the problem is a authentication problem, the script is not found (this is the case here), the user error, or some issues have occurred in the code. Add some simple code to make this error more specific. Refer to listing 8, which is responsible for handling unfound scripts or authentication errors. Specific Messages are provided when these errors occur.

Listing 8. Check the valid status code

Function updatepage (){
If (request. readystate = 4 ){
If (request. Status = 200 ){
VaR response = request. responsetext. Split ("| ");
Document. getelementbyid ("order"). value = response [0];
Document. getelementbyid ("Address"). innerhtml =
Response [1]. Replace (// n/g, "<br/> ");
} Else if (request. Status = 404 ){
Alert ("requested URL is not found .");
} Else if (request. Status = 403 ){
Alert ("Access denied .");
} Else
Alert ("status is" + request. status );
}
}

Although this is still quite simple, it does provide some useful information. Figure 6 shows the same error as Figure 5, but this error handling code shows users or programmers what happened better.

Figure 6. Special error handling

In our own applications, we can consider clearing the user name and password when authentication fails and adding an error message to the screen. We can use a similar method to better handle errors of the script or other 400 type that cannot be found (for example, 405 indicates that unacceptable request methods such as sending HEAD requests are not allowed, and 407 indicates that proxy authentication is required ). However, no matter which option is used, you must start from processing the status code returned by the server.

Other request types

If you really want to control the XMLHTTPRequest object, you can finally implement this function-Add the head request to the instruction. In the first two articles, we have introduced how to generate GET requests. In an article to be published soon, you will learn how to send data to the server using post requests. However, in the spirit of enhancing error handling and information collection, you should learn how to generate HEAD requests.

Generate request

In fact, it is very simple to generate a head request. You can use "head" (instead of "get" or "Post") as the first parameter to call the open () method, as shown in listing 9.

Listing 9. Generate a head request using Ajax

Function getsalesdata (){
Createrequest ();
VaR url = "/boards/servlet/updateboardsales ";
Request. Open ("head", URL, true );
Request. onreadystatechange = updatepage;
Request. Send (null );
}

When you generate a head request like this, the server does not return a real response like a get or POST request. On the contrary, the server only returns the header of the resource, which includes the last modification time of the content in the response, whether the requested resource exists, and many other useful information. You can use this information to learn about resources before the server processes and returns resources.

The simplest thing you can do for such a request is to simply output the content of all the response headers. This allows you to understand what a head request can use. Listing 10 provides a simple callback function to output the content of the Response Header obtained from the head request.

Listing 10. output the response header content obtained from the head request

Function updatepage (){
If (request. readystate = 4 ){
Alert (request. getAllResponseHeaders ());
}
}

See Figure 7, which shows the Response Headers returned by a simple Ajax application from a head request sent to the server.

You can use these headers (from server type to content type) to provide other information or functions in Ajax applications.

Check URL

You have seen how to check the 404 error when the URL does not exist. If this becomes a common problem-a specific script or servlet may be missing-you may want to check the URL before generating a complete get or POST request. To implement this function, generate a head request and check Error 404 in the callback function. Listing 11 provides a simple callback function.

Listing 11. check whether a URL exists

Function updatepage (){
If (request. readystate = 4 ){
If (request. Status = 200 ){
Alert ("url exists ");
} Else if (request. Status = 404 ){
Alert ("url does not exist .");
} Else {
Alert ("status is:" + request. status );
}
}
}

Honestly, this code is not very valuable. The server must respond to the request and construct a response to fill in the response header with the content length. Therefore, it cannot save any processing time. In addition, this takes as much time as it takes to generate a request and use a head request to check whether a URL exists, because it generates a request using get or post, instead of handling error codes as shown in listing 7. However, sometimes it is very useful to know exactly what is available at present. You will never know when creativity will pop up or when HEAD requests will be required!

Useful HEAD requests

You will find that one of the most useful fields of head requests is to view the length or type of content. In this way, you can determine whether to send back a large amount of data to process the request, and whether the server tries to return binary data, rather than HTML, text, or XML (in Javascript, these three types of data are easier to process than binary data ).

In these cases, you only use the appropriate header name and pass it to the getResponseHeader () method of the XMLHTTPRequest object. Therefore, to obtain the response length, you only need to call request. getResponseHeader ("Content-Length ");. To obtain the content type, use request. getResponseHeader ("Content-Type ");.

In many applications, generating a head request does not add any function, or even slows down the request speed (by forcibly generating a head request to obtain the response data, then, use a get or POST request to actually obtain the response ). However, when you are not sure about the script or server components, you can use the head request to obtain some basic data without actually processing the response data, it does not require a large amount of bandwidth to send responses.

Conclusion

For many Ajax and web programmers, the content described in this article seems too advanced. What is the value of generating HEAD requests? Under what circumstances do I need to explicitly process the redirection status code in JavaScript? These are good questions. For simple applications, the answer is that the value of these advanced technologies is not very great.

 

However, web is no longer just a place to implement simple applications; users have become more advanced, and customers expect better stability and more advanced error reports, if the application has 1% downtime, the manager may be dismissed.

Therefore, your work is not limited to simple applications, but requires a deeper understanding of XMLHttpRequest.

·If you can consider various readiness statuses-and understand the differences between these readiness statuses in different browsers-you can quickly debug the application. You can even develop some creative functions based on the readiness status and return the status of requests to users and customers.
·If you want to control the status code, you can set an application to handle script errors, unexpected responses, and Edge Conditions. The result is that the application can work normally at all times, not only when everything is normal.
·This capability is added to generate HEAD requests, check whether a URL exists, and check whether a file has been modified. This ensures that the user can obtain a valid page, the information users see is up-to-date (and most importantly), which surprised them how robust and general the application is.
The purpose of this article is not to make your application look gorgeous, but to help you remove the yellow spotlight and highlight the beauty of the text, or look more like a desktop. Although these are Ajax functions (which will be introduced in a few articles later), they are like a layer of cream on the cake surface. If you can use ajax to build a solid foundation so that the application can handle errors and problems well, the user will return to your site and application. In the next article, we will add this intuitive technique, which will shake the customer with excitement. (Seriously, you do not want to miss 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.