Learning notes: Understanding Ajax Part 1: Advanced requests and responses in Ajax (continued)

Source: Internet
Author: User

Master Ajax Part 1: Advanced requests and responses in Ajax (continued) 3rd

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", it is throughXMLHttpRequestObjectstatusAttribute. 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.

                           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.

 

Before going into the details about the error, we need to discuss aboutNot RequiredConcerned: 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 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.

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, calledEdge case)-- They only occur in some very special circumstances, and all of them 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.

 

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.

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.

                           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.

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.

 

If you really want to controlXMLHttpRequestTo add the HEAD request to the command. 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.

 

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 callopen()Method, as shown in listing 9.

                           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 returnsHeader)This 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.

                           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.

 

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.

                           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!

 

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 itXMLHttpRequestObjectgetResponseHeader()Method. Therefore, to obtain the response length, you only need to callrequest.getResponseHeader("Content-Length");. To obtain the content type, userequest.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.

 

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.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.