[Four days learn Ajax] Learn Ajax tutorial The third day, advanced requests and responses in Ajax

Source: Internet
Author: User
Tags add error code error handling functions gettext header net split
Ajax| Advanced | tutorials | request | response


For many WEB developers, it is only necessary to generate simple requests and receive simple responses, but for developers wishing to master Ajax, the HTTP status code, the ready state, and the XMLHttpRequest object must be fully understood. In this article, Brett McLaughlin introduces you to a variety of status codes and shows how the browser handles them, and this article gives you a rare HTTP request that is used in Ajax.



In the previous article in this series, we will detail the XMLHttpRequest object, which is the center of an AJAX application that handles requests for server-side applications and scripts and processes data returned from server-side components. Because all AJAX applications use the XMLHttpRequest object, you might want to familiarize yourself with the object so that Ajax can perform better.



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



· HTTP Ready State
· HTTP Status Code
• Types of requests that can be generated



These three sections are the factors to consider when constructing a request, but there is little to introduce them. However, if you want to learn more than just the common sense of Ajax programming, you need to be familiar with the ready state, the status code, and the content of the request itself. When a problem occurs in an application--a problem that always exists--if you can correctly understand the readiness, how to generate a head request, or the exact meaning of the 400 status code, you can debug the problem in 5 minutes instead of spending 5 hours in frustration and confusion.



Let's take a look at the HTTP ready state first.



Deep understanding of HTTP ready State



You should remember that in the previous article the XMLHttpRequest object had a property named ReadyState. This property ensures that the server has completed a request and typically uses a callback function to read the data from the server to update the contents of the Web form or page. Listing 1 gives a simple example (this is an example of the previous article in this series), see Resources.






XMLHttpRequest or XMLHttp: Changing the name of a rose



microsoft™ and Internet Explorer use an object named XMLHttp instead of a XMLHttpRequest object, while Mozilla, Opera, Safari, and most non-Microsoft browsers make The latter is used. For simplicity's sake, I'll simply refer to both objects as XMLHttpRequest. This is consistent with what we see on the Web and with Microsoft's intent to use XMLHttpRequest as the object of request in Internet Explorer 7.0. (see part 2nd for more information on this issue .) )



Listing 1. Handling the response of a server in a 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 clearly the most common (and simplest) use of the ready state. As you can see from the number "4", there are several other ready states (which you have seen in the previous article-see Resources):



• 0: The request was not initialized (the open () was not called yet).
• 1: The request has been established, but has not been sent (send () has not been called yet).
• 2: The request has been sent and is being processed (usually the content header can now be fetched from the response).
• 3: The request is in process; some of the data is usually available in the response, but the server has not completed the response generation.
• 4: The response is complete; you can get and use the server's response.



If you want to learn more than just the basics of Ajax programming, you need to know not only these states, when they appear, and how to use them. First, you need to learn what kind of request status you might encounter in each of the ready states. Unfortunately, this is not intuitive and involves several special situations.



Stealth Ready Status



The first ready state is characterized by a readyState property of 0 (ReadyState = = 0), which indicates an uninitialized state. Once you call Open () on the Request object, this property is set to 1. Because you usually call open () immediately after a pair of requests are initialized, you rarely see the state of readyState = 0. In addition, the uninitialized ready state is not really useful in the actual application.



However, to satisfy our interest, see Listing 2, which shows how to get this ready state when ReadyState is set to 0 o'clock.



Listing 2. Get 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 the function used by a Web page call to start a request, such as clicking a button. Note You must view the ready state before calling open (). Figure 1 shows the results of running this application.



Figure 1. Ready Status 0






Obviously, this does not bring you much benefit; you need to make sure that the open () function has not been invoked very rarely. In the true case of most Ajax programming, the only use of this ready state is to generate multiple requests between functions using the same XMLHttpRequest object. In this (uncommon) scenario, you may want to make sure that the requested object is in an uninitialized state (readyState = 0) before generating a new request. This is actually to make sure that another function does not use this object at the same time.



View the ready status of the request being processed



In addition to the 0 ready state, the request object needs to go through several other ready states of the typical request and response in turn, ending with a ready state of 4. This is why you can see the line of if (Request.readystate = 4) In most of the callback functions, it ensures that the server has finished processing the request, and now it is safe to update the WEB page or to operate on the data returned from the server.



It is easy to see the process of this state happening. If the ready state is 4, we will not only run the code in the callback function, but also output the ready state each time the callback function is invoked. Listing 3 shows an example of how this function is implemented.



When 0 equals 4 o'clock



When multiple JavaScript functions use the same Request object, you need to check the ready state 0来 ensure that the request object is not in use, and this mechanism can cause problems. Because readyState = = 4 represents a completed request, so you will often find that those in the ready state that are not currently in use are still set to 4--because the data returned from the server has been used, but nothing has changed since they were set to the ready state. There is a function abort () that will reset the request object, but this function is not really used for this purpose. If you must use more than one function, it is best to create and use a function for each function instead of sharing the same object among multiple functions.



Listing 3. View Ready Status



function Updatepage () {
Output the current Ready state
Alert ("Updatepage () called with ready state of" + request.readystate);
}



If you're not sure how to run this function, you need to create a function and then call the function in a Web page and have it send a request to the server-side component (for example, the function given in Listing 2, or the example given in parts 1th and 2nd of this series). Make sure that the callback function is set to Updatepage () when the request is established, and that the onReadyStateChange property of the request object can be set to Updatepage () to implement this setting.



This code is an exact display of onreadystatechange meaning-call updatepage () every time the ready state of the request changes, and then we can see a warning. Figure 2 shows an example of a call to this function, where the ready state is 1.



Figure 2. Ready Status 1






You can try to run this code yourself. Put it in a Web page, and then activate the event handler (click the button, tab between the fields to toggle the focus, or use any method set to trigger the request). This callback function will run multiple times--every ready state will change--you can see a warning for each ready state. This is the best way to track the stages that a request goes through.



Inconsistencies in browsers



After you have a basic understanding of the process, try to access your page from several different browsers. You should notice how each browser handles these readiness states in a inconsistent way. For example, in Firefox 1.5, you will see the following ready states:



·1
2
3
4



That's not surprising, because each request status is represented here. However, if you use Safari to access the same application, you should see--or not see--some interesting things. The following are the states seen in Safari 2.0.1:



2
3
4



Safari actually discards the first ready state, and there's no obvious reason why, but that's how safari works. This also illustrates an important issue: although it is a good idea to make sure that the state of the request is 4 before using the data on the server, the code that relies on the ready state of each transition period does have different results on different browsers.



For example, when you use Opera 8.5, the status of the readiness displayed is even worse:



3
4



Finally, Internet Explorer displays the following status:



·1
2
3
4



If you have a problem with the request, this is the first thing to discover. The best way to do this is to test the Internet Explorer and Firefox-you'll see all 4 states, and you can check each state of the request.



Next we'll look at the response side.



Response data under the microscope



Once we understand the various ready states that occur during the request process, we can then look at another aspect of the XMLHttpRequest object, the--responsetext attribute. Looking back at what we've covered in the previous article, we can see that this property is used to fetch data from the server. Once the server completes processing the request, it can put any data required by the response request data into the responsetext of the request. The callback function can then use the data, as shown in Listing 1 and listing 4.



Listing 4. Using the response returned on 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 fairly simple; Listing 4 is slightly more complex, but they start with a ready state and get the value of the ResponseText property.



View the response text for a request



Like the ready state, the value of the ResponseText property changes throughout the life cycle of the request. To see this change, test the requested response text with the code shown in Listing 5, and their ready state.



Listing 5. Testing ResponseText Properties



function Updatepage () {
Output the current Ready state
Alert ("Updatepage () called with ready state of" + Request.readystate +
"And a response text of '" + Request.responsetext + "'");
}



Now 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 the possible ready states in the request process. For example, in Ready state 2, there is no responsetext defined (see Figure 3); If the JavaScript console is already open, you will see an error.



Figure 3. Response text with a ready status of 2






However, in Ready state 3, the server has placed a value in the ResponseText attribute, at least in this case (see Figure 4).



Figure 4. Response text with a ready status of 3






You will see that a ready state of 3 response is different for each script, every server, and even every browser. However, this is still useful in debugging applications.



Get Security data



All documents and specifications emphasize that the data is safe to use only if the ready state is 4 o'clock. Trust me, when the Ready status is 3 o'clock, you rarely find a situation where you cannot get data from the ResponseText property. However, it is not a good idea to rely on your own logic in your application in the Ready state 3-Once you've written code that relies on the complete data in Ready State 3, you're almost ready to take responsibility for the incomplete data at that time.



It's a good idea to provide some feedback to the user that the response will soon be in a ready state 3 o'clock. Although using functions such as alert () is obviously not a good idea-using Ajax and then using a warning dialog box to block the user is obviously a mistake-you can update the fields on the form or page as the ready state changes. For example, for a ready state, you would set the width of the progress indicator to 25%, for the ready state and second, to set the width of the progress indicator to 50%, for the ready state 3来 says that you want to set the width of the progress indicator to 75% and set the progress indicator to 100% (complete) When the ready state is 4 o'clock.



Of course, as you've seen, this approach is very smart, but it's dependent on the browser. You will never see the top two ready states on Opera, and there is no first (1) on Safari. For this reason, I left this code as an exercise, not included in this article.



Now you should take a look at the status code.



In-depth understanding of HTTP status Codes



With the ready state and the responsiveness of the servers you learned in AJAX programming techniques, you can add another level of complexity to your AJAX application--using the HTTP status code. The code is nothing new to Ajax. Since the advent of the Web, they have already existed. You may have seen several status codes in your Web browser:



• 401: Unauthorized
• 403: Prohibited
• 404: Not Found



You can find more status codes (see Resources for a complete list). To add another layer of control and response (and more robust error handling) mechanisms for AJAX applications, you need to view the status codes in the request and response appropriately.



200: Everything is fine



In many Ajax applications, you will see a callback function that is responsible for checking the ready state and then continuing to take advantage of the data returned from the server response, as shown in Listing 6.



Listing 6. Ignore callback function for 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 is a short-sighted and error-proof method for Ajax programming. If the script requires authentication and the request does not provide a valid certificate, the server returns an 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 answer is not what the request expects). Ultimately, users do not get valid data, and when JavaScript attempts to use server data that does not exist, a serious error can occur.



It takes minimal effort to ensure that the server not only completes a request, but also returns a "all good" status code. This code is "200", which is reported by the XMLHttpRequest object's Status property. To ensure that the server not only completes a request, but also reports an OK state, add another check function to your callback function, as shown in Listing 7.



Listing 7. Check valid status codes



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 confirm that there is a problem and that the user sees a useful error message, not just a page made up of data that was taken out of context, without any explanation.



Redirecting and rerouting



Before delving into the content of the error, it is necessary to discuss a problem that does not require attention when using Ajax-redirect. In the HTTP status code, this is the status code for the 300 series, including:



• 301: Permanent Mobile
• 302: Find (Request redirected to another Url/uri)
• 305: Using a proxy (the request must use a proxy to access the requested resource)



Ajax programmers may not care too much about redirection, because of two reasons:



• First, Ajax applications are typically written for a particular server-side script, servlet, or application. Ajax programmers are not so clear about components that you don't see and disappear. So sometimes you know that the resource has moved (because you moved it, or moved it by some means), and then you want to modify the URL in the request, and it won't happen again.
One of the more important reasons is that AJAX applications and requests are encapsulated in a sandbox. This means that the domain that provides the Web page that generates the AJAX request must be the domain that responds to those requests. Therefore, the Web page provided by ebay.com cannot generate an AJAX-style request for a script that runs on Amazon.com, nor does an AJAX application on the ibm.com issue the servlets that runs on the netbeans.org. Please.
• The result is that your request cannot be redirected to another server without creating a security error. In these cases, you will not get the status code at all. Usually a JavaScript error is generated in the debug console. Therefore, after fully considering the status code, you can completely ignore the problem of redirecting 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. Usually a JavaScript error is generated in the debug console. Therefore, after fully considering the status code, you can completely ignore the problem of redirecting code.



Error



Once you receive status code 200 and realize that you can largely ignore the status code for the 300 series, the only set of code you need to worry about is the code for the 400 series, which illustrates the different types of errors. Take a look at listing 7 and note that when handling errors, only a few common error messages are exported to the user. While this is a step in the right direction, it is still not very useful to tell the users and programmers who are engaged in application development what is going on.



First, we want to add support for pages that are not found. This should not actually happen in most product systems, but this is not uncommon when the test script location changes or the programmer enters the wrong URL. If you can report the 404 errors Naturally, you can provide more help to the troubled users and programmers. 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 situation and difficult situation



See now, some novice programmers may be what this is about to discuss what content. One thing you need to know: less than 5% of Ajax requests need to use a ready state like 2, 3, and a status code such as 403 (in fact, this ratio may be closer to 1% or less). These situations are very important, called boundary conditions (Edge case)--they only happen in very special situations, and all of them encounter the strangest problems. Although these situations are not common, these border situations occupy 80% of the problems that most users encounter!



For a typical user, the fact that the application is working 100 times is usually forgotten, but the application can be remembered with a single error. If you can handle boundary conditions (or difficult situations) well, you can provide a satisfying return for users who visit the site again.



Figure 5. Common error Handling





The user cannot determine whether the problem is an authentication issue, a script is not found (this is the case here), a user error, or some place in the code that is having problems. Adding some simple code can make this error more specific. Please refer to listing 8, which is responsible for handling cases where no script has been found or where the authentication error occurred, giving a specific message when these errors occur.



Listing 8. Check valid status codes


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);
}
}


While this is still fairly simple, it does provide a lot of useful information. Figure 6 shows the same error as Figure 5, but this time the error-handling code gives the user or programmer a better indication of what's going on.



Figure 6. Special error Handling






In our own application, consider clearing the user name and password when a certification failure occurs, and adding an error message to the screen. We can use a similar approach to better handle errors that cannot be found in scripts or other 400 types (for example, 405 means that an unacceptable request method such as sending a head request is not allowed, and 407 indicates that a proxy authentication is required). However, whichever choice you take, you need to start with the status code returned on the server.



Other Request types






Build Request



Actually generating the head request is very simple; you can invoke the open () method using "head" instead of "get" or "POST" as the first parameter, as shown in Listing 9.



Listing 9. Using Ajax to generate a head request



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. Instead, the server returns only the header of the resource, which includes the time when the content was last modified in the response, whether the request resource exists, and many other useful information. You can use this information to understand information about resources before the server processes and returns resources.



The simplest thing you can do for such a request is simply to output the contents of all the response headers. This will give you an idea of what you can use with the head request. Listing 10 provides a simple callback function to output the contents of the response header obtained from the head request.



Listing 10. Output the contents 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 from a simple Ajax application that sends a head request to the server.






You can use these headers individually (from server type to content Type) to provide additional information or functionality in an Ajax application.



Check URL



You have seen how to check for 404 errors when the URL does not exist. If this becomes a common problem--probably missing a particular script or servlet----then you might want to check the URL when generating a full get or POST request. To do this, generate a head request and then check for a 404 error in the callback function; Listing 11 shows a simple callback function.



Listing 11. Check if 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);
}
}
}



To be honest, the value of this code is not too great. The server must respond to the request and construct a response to fill the response header of the content length, so no processing time can be saved. In addition, it takes as much time to build a request and use the head request to see if the URL exists, because it generates a request to use either GET or POST, not just the error code as shown in Listing 7. However, sometimes it is useful to know exactly what is currently available; you never know when your creativity will burst or when you need a HEAD request!



A useful head request



One area you'll find useful for head requests is to see the length of the content or the type of content. This determines whether you need to send back large amounts of data to process requests, and whether the server attempts to return binary data, rather than HTML, text, or XML (in JavaScript, these 3 types of data are easier to handle than binary data).



In these cases, you use only the appropriate header names and pass them to the getResponseHeader () method of the XMLHttpRequest object. So to get the length of the response, you only need to call Request.getresponseheader ("Content-length");. To get the content type, use Request.getresponseheader ("Content-type");.



In many applications, generating a head request does not add any functionality, and may even result in slower requests (by forcing a head request to get data about the response, and then actually getting the response using a GET or POST request). However, when you are unsure about a script or server-side component, use the head request to get some basic data without actually processing the response data or requiring a large amount of bandwidth to send the response.



Conclusion



For many Ajax and WEB programmers, the content described in this article seems to be too advanced. What is the value of generating a head request? In what situations do you need to explicitly handle redirection state code in JavaScript? These are all good questions; for simple applications, the answer is that the value of these advanced technologies is not very large.



However, the WEB is no longer the place to simply implement a simple application; The user has become more advanced, customers expect better stability, more advanced error reporting, and if the application has 1% downtime, the manager may be dismissed.



So your work cannot be confined to simple applications, but requires a deeper understanding of XMLHttpRequest.



· If you can consider the various readiness states-and understand the differences between these ready states in different browsers-you can quickly debug your application. You can even develop creative features based on the ready state and return the requested status to users and customers.
· If you want to control the status code, you can set up your application to handle script errors, unexpected responses, and edge conditions. The result is that the application works at all times, not just when everything is normal.
· Increase the ability to generate head requests, checking to see if a URL exists, and confirming that a file has been modified, ensures that the user can get a valid page, the information that the user sees is up to date, and (most importantly) how robust and generic 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 the desktop. Although these are Ajax features (described in subsequent articles), they are like a layer of cream on the surface of a cake. If you can use Ajax to build a solid foundation in which applications can handle errors and problems well, users will return to your site and application. In the following article, we will add this intuitive technique, which will make the customer shiver with excitement. (Seriously, you certainly don't 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.