Chapter 3: Advanced Requests and Responsions in Ajax

xiaoxiao2021-04-04  244

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

HTTP Ready Status HTTP Status Code can generate the request type

These three sections are factors to consider when constructing a request; but the contents of these topics are too small. However, if you not only want to understand the common sense of Ajax programming, but want to know more, you need to be familiar with the ready state, status code, and request itself. When the application has a problem - this problem always exists - if it is possible to properly understand the ready state, how to generate a HEAD request or the exact meaning of the status code of 400, you can debug the problem within 5 minutes, not After a variety of setbacks and confusion, it spent 5 hours.

XMLHTTPREQUEST or XMLHTTTP: Turn your name Rose MicrosoftTM and Internet Explorer uses an object called XMLHTTP instead of xmlhttpRequest objects, while Mozilla, Opera, Safari, and most non-Microsoft browsers are used. For the sake of simplicity, I simply referred to the two objects as XMLHttpRequest. This is in line with our situation in the Web, in line with Microsoft to use XMLHttpRequest in Internet Explorer 7.0 as the intent of the request object. (For more information on this issue, see Part 2.)

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

In-depth understanding of HTTP ready state

You should still remember that the XMLHttpRequest object in the previous article has an attribute called ReadyState. This attribute ensures that the server has completed a request, usually using a callback function reads data from the server to update the contents of the web form or page. Listing 1 gives a simple example (this is also an example in this series - see Resources).

Listing 1. Processing the server's 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, '
);

Else

Alert ('status is' request.status);

}

}

This is obviously the most common (and the simplest) usage of ready state. As you can see from the numbers '4', there are several other ready state (you have also seen this list in the previous article - see the reference):

0: The request is not initialization (Open ()) is not called. 1: The request has been established, but has not been sent (SEND ()) yet. 2: The request has been sent, in processing (usually, the content header can now be obtained from the response). 3: Requests in processing; usually some data in response can be used, but the server has not generated the response. 4: Response has been completed; you can get and use the server's response.

If you want not only to understand the basic knowledge of AJAX programming, then not only you need to know these states, you know where these status appears, and how to use these states. First, you need to learn which request state may be encountered in each ready state. Unfortunately, this is not intuitive and will involve several special situations.

Hidden ready state

The first type of ready state is that the readyState property is 0 (readyState == 0), indicating that the unintrodunled state. Once the request object is invoked, this property is set to 1. Since you usually call Open () immediately after a pair of requests, you will find the status of ReadyState == 0. In addition, the uninitialized ready state is not really used in the actual application.

However, in order to meet our interest, see Listing 2, which shows how to get this ready state when ReadyState is set to 0.

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 the web page call to start the request (for example, click on a button). Note You must view ready state before calling Open (). Figure 1 shows the result of running this application.

Figure 1. Ready 0

When 0 is equal to 4 When multiple JavaScript functions use the same request object, you need to check ready state 0 to ensure that this request object is not in use, this mechanism will generate a problem. Since readyState == 4 indicates a completed request, you often find that the request object that is currently not in use is still set to 4 - this is because the data returned from the server has been used. However, no change is made after they are set to be ready. There is a function Abort () reset the request object, but this function is not truly used for this purpose. If you must use multiple functions, it is best to create and use a function for each function, rather than sharing the same object between multiple functions.

Obviously, this does not have much benefits to you; it is necessary to make sure that the Open () function has not been called. In the true case of most AJAX programming, the only way to use the same XMLHttpRequest object is generated between multiple functions between multiple functions. In this case (uncommon) case, you may want to make sure that the request object is in an uninited state before generating a new request (ReadyState == 0). This is actually to ensure that another function does not use this object at the same time.

View the ready state of the request being processed

In addition to the 0 ready state, the request object also needs to experience a typical request and other similar states of the response, and finally end in the form of ready state 4. That's why you can see if IF (Request.ReadyState == 4) in most callback functions; it ensures that the server has completed the process of requesting, and now you can safely update the web page or return it according to the server from the server. The data is operated. The process to see this state is very simple. If the ready state is 4, we must not only run the code in the callback function, but also output the ready state at each call the callback function. Listing 3 gives an example of implementing this function.

Listing 3. View Ready 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, then call this function in the web page, and let it send a request to the server side (such as the function given by Listing 2, or the first article The examples given in Parts and Part 2). Be sure to set the callback function to updatePage () when establishing a request (); to implement this setting, you can set the onReadyStateChange property of the request object to UpdatePage ().

This code is an exact display of OnReadyStateChange meaning - UpdatePage () is called when the ready state of each request is changed, and then we can see a warning. Figure 2 shows an example in which the function is called, where the ready state is 1.

Figure 2. Ready 1

You can try to run this code. Place it in a web page, then activate the event handler (click the button, press the Tab key to switch the focus, or use any method of setting to trigger the request). This callback function will run multiple times - each ready state changes - you can see a warning for each ready state. This is the best way to track the various stages experienced by the request.

The inconsistency of browsers

After having a basic understanding of this process, try accessing your page from a few different browsers. You should notice how each browser handles these ready status is inconsistent. For example, in Firefox 1.5, you will see the following:

1 2 3 4

This is not surprising, because each request state is expressed here. However, if you use Safari to access the same application, you should see - or not see - some interesting things. The following is the status seen in Safari 2.0.1:

2 3 4

Safari actually discarded the first ready state, and there is not any obvious reason to do this; but this is how Safari works. This also illustrates an important issue: Although the status of the request is 4 is a good idea before using the data on the server, but the code depends on each transition-ready state is indeed different on different browsers. the result of.

For example, when using Opera 8.5, the ready state display is worse:

3 4

Finally, Internet Explorer will display the following:

1 2 3 4

If you encounter a request for the request, this is the first place to find problems. The best way is to test in Internet Explorer and Firefox - you will see all of these four states and check the case where the request is located.

Let's take a look at the situation in response.

Response data under the microscope

Once we understand each of the ready states that occur during the request, you can take a look at another aspect of the XMLHTTPRequest object - ResponseText property. Recall the content we introduced in the previous article, you can know that this property is used to get data from the server. Once the server completes the processing of the request, any data required by the response request data can be placed in the requested responseText. Then the callback function can use these data, as shown in Listing 1 and Listing 4.

Listing 4. Response returned on the server

Function updatePage () {

if (Request.ReadyState == 4) {

Var newstotal = request.responsetext;

Var totalsoldel = document.getElementByid ('Total-sold');

Var netprofitel = document.getlementByid ('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; the list 4 is slightly complicated, but they have to check ready state 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 property will also change in the life cycle of the entire request. To view this change, use the code shown in Listing 5 to test the request response text, and their ready state.

Listing 5. Test the responseText property

Function updatePage () {

// Output The Current Ready State

Alert ('updatePage () Called with ready state of' request.readystate

'and a responsponse text of' ' request.responsetext ' ');

}

Now open the web application in your browser and activate your request. To better see this code, use Firefox or Internet Explorer, because both browsers can report all possible ready states during the request. For example, in Ready State 2, there is no responsetext (see Figure 3); if the JavaScript console has also been opened, you will see an error. Figure 3. Response text of the ready state 2

However, in the Ready State 3, the server has already placed a value in the ResponseText property, at least in this example (see Figure 4).

Figure 4. Response text of the ready state 3

You will see a response of the ready status 3 in each script, each server or even every browser is different. However, this is still very useful in debugging applications.

Get safety data

All documents and specifications have emphasized that data can be safely used when data is 4 when ready. Believe me, when you are 3, you rarely find the situation where you can't get data from the ResponseText property. However, in the application, the logic depends on the ready state 3, is not a good idea - once you write the code that relies on the full data of the ready state 3, almost you will be responsible for the incomplete problem of the data at the time. .

A preferred approach is to provide some feedback to the user, indicating that there will be a response when it is in the ready state. Although functions such as using ALERT () is obviously not a good idea - use AJAX and use a warning dialog to block users obviously wrong - but you can update the form or page during the ready state changes. For example, for the ready state 1 to set the width of the progress indicator to 25%, the width of the progress indicator is set to 50% for the ready state 2, and the progress indicator should be regarded for the ready state 3. The width is set to 75%, and the width of the progress indicator is set to 100% (completed) when the inventive state is 4.

Of course, as you have already seen, this method is very smart, but it is dependent on the browser. On Opera, you will never see the first two ready state, and there is no first (1) on Safari. For this reason, I will leave this code for exercises, but not included in this article.

Take a look at the status code now.

In-depth understanding of HTTP status code

With a response to the server you have learned in Ajax programming technology, you can add additional primary complexity for the Ajax application - this is used by HTTP status code. These codes are not fresh for Ajax. Since the appearance of Web, they have existed. In a web browser, you may have seen several status code:

401: Unauthorized 403: No 404: Didn't find

You can find more status code (see Resources for a full list). To add a layer of control and response (and more robust error handling) mechanism for the Ajax application, you need to view the status code in the request and response.

200: everything is normal

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

Listing 6. Ignore the callback function of the 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, '
);

}

}

This proof for Ajax programming is a short visual and wrong way. If the script needs to be authenticated, the request does not provide a valid certificate, then the server returns an error code such as 403 or 401. However, since the server responds to the request, the ready state is set to 4 (even if the answer is not the desired expectation). Finally, the user does not get valid data, and when JavaScript tries to use the unsaved server data, it may have a serious error.

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

Listing 7. Check 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, '
);

Else

Alert ('status is' request.status);

}

}

By adding these lines of code, you can confirm that there is a problem, the user will see a useful error message, not just a page consisting of a data made by the breakdown, without any explanation.

Redirect and re-row

Before introducing the contents of the error, we must discuss the issue of issues related to one when using Ajax - redirect. In the HTTP status code, this is a 300 series status code, including:

301: Permanent Mobile 302: Find (request is reset to another URL / URI) 305: Using a proxy (request must use a proxy to access the requested resources)

Ajax programmers may not care about the issue of redirection, because two reasons:

First, Ajax applications are usually written for a specific server-side script, servlet, or application. For components that you can't see, Ajax programmers are not very clear. So sometimes you know that the resource has been moved (because you move it, or move it through some means), you will modify the URL in the request and will not touch this result. One more important reason is that Ajax applications and requests are packaged in the sandbox. This means that the domain that provides a web page that generates an AJAX request must be a domain that responds to these requests. So the web page provided by eBay.com cannot generate an Ajax style request for a script running on Amazon.com; Ajax applications on IBM.com cannot request a request for servlets running on NetBeans.org. . The result is that your request cannot be redirected to other servers without a security error. In these cases, you will not get status code at all. A JavaScript error is usually generated in the debug console. Therefore, after sufficient consideration of the status code, you can completely ignore the problem of redirection code.

The border situation and difficulties see now, some newbie programmers may be what content will be discussed. One thing needs to know: Only less than 5% of the AJAX request requires the use of ready state such as 2, 3 and status code such as 403, which may be closer to 1% or even less) . These situations are very important, called the border case - they will only happen in some very special cases, which are the most quite issues. Although these situations are not common, these borders have occupied 80% of the issues encountered by most users! For typical users, the application is usually working in normal work, but it is usually forgotten. Applications will be clearly remembered by them. If you can handle border conditions (or difficult), you can provide a satisfactory return for users who have access to the site.

error

Once the status code 200 is received and realizes that the 300 series of state code can be largely ignored, the unique set of code that you need is the 400 series of code, which illustrates different types of errors. Take a look at Listing 7, and pay attention to the user only to output a few common error messages when processed. Although this is a step forward in the right direction, but what problems do they have to tell for applications developed, these news is still not too much.

First, we have to add support for the page that is not found. In fact, this should not appear in most product systems, but when the test script location changes or programmers enter the wrong URL, this situation is not rare. If you can naturally report 404 errors, you can provide more help for those who are troublesome and programmers. For example, if one 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.

Figure 5. Common error handling

Users cannot determine the problem is the authentication problem. Didn't find the script (this is this situation), the user error is still a problem in some places in the code. Add some simple code to make this error more specific. Refer to Listing 8, which is responsible for handling the case where the script that has not been found or the error occurs, and the specific message will be given when these errors appear.

Listing 8. Check 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, '
);

} 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 errors as Figure 5, but this time the error handling code better illustrates what happens to the user or programmer.

Figure 6. Special error handling

In our own application, you can clear the username and password when the authentication failed, and add an error message to the screen. We can use similar methods to better process errors that cannot be found or other 400 types (for example, 405 means that the unacceptable request method such as sending the HEAD request is not allowed, and 407 indicates that proxy authentication). However, no matter which choice is used, it is necessary to start from the status code returned on the server.

Other request types

If you really want to control the XMLHttpRequest object, you can consider final implementation - add the HEAD request to the instruction. In the first two articles, we have already introduced how to generate a GET request; in an article that is about to publish, you will learn about the knowledge of using the POST request to send data to the server. However, in the spirit of enhancing error handling and information collection, you should learn how to generate a HEAD request.

Request request

In fact, the HEAD request is very simple; you can use 'head' (not '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, the server does not return a real response like a GET or POST request. Instead, the server will only return the header of the resource, which includes the time of the response to the last modification of the content, requiring the resource to exist and many other useful information. You can use this information before the server is handled and returned to the resource to learn about the information about resources.

The easiest thing to do with this request is to simply output all the contents of the response header. This allows you to know what you can use through the HEAD request. Listing 10 provides a simple callback function to output the contents of the response head obtained from the HEAD request.

Listing 10. Output 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 head returned from a simple Ajax application that is sent from a HEAD request emitted to the server.

Figure 7. Responsive head of HEAD request

You can use these headers separately (from the server type to content type) to provide additional information or features in the Ajax application.

Check URL

You have seen how to check 404 errors when the URL does not exist. If this becomes a common problem - may be missing a specific script or servlet - then you might want to check this URL before generating a complete GET or POST request. To achieve this feature, generate a HEAD request, then check 404 errors in the callback function; Listing 11 gives 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);

}

}

}

Honestly, the value of this code is not too big. The server must respond to the request and constructed a response to fill the header length of the content length, so it does not save any processing time. In addition, this takes time with the generation request and uses the HEAD request to see if there is a need for the required time, because it is to generate a request to use GET or POST, not just as shown in Listing 7 to process the error code. . However, sometimes it is very useful to know what is currently available; you will never know when creative will burst or when you need a HEAD request!

Useful HEAD request

You will find that the HEAD request is a very useful area is the type used to view the length or content of the content. This makes it possible to determine if a large amount of data is needed to process the request, and the server attempts to return binary data, not HTML, text, or XML (in JavaScript, these three types of data are more easier than binary data).

In these cases, you only use the right name and passed it to the getResponseHeader () method of the XMLHttpRequest object. Therefore, you have to get the length of the response, just call Request.getResponseHead ('Content-length') ;. To get the content type, use Request.getResponseHeader ('content-type');

In many applications, generating a HEAD request does not add any functions, and may even result in slowing the request speed (by enforcing a HEAD request to obtain data about the response, then use a GET or POST request to truly get a response) . However, when you are not sure about script or server-side components, you can get some basic data without the need to truly process the response data, nor does it require a large amount of bandwidth to send a response.

Conclude

For many Ajax and web programmers, the content present in this article seems too advanced. What is the value of generating a HEAD request? Under what circumstances need to be displayed in JavaScript to process the redirection status code? These are very good problems; for simple applications, the answer is that the value of these advanced technology is not very large. However, the Web is no longer only necessary to implement simple applications; users have become more advanced, customers expect to get better stability, more advanced error reporting, if the application has 1% timestock, Then manager may be fired.

So your work cannot be limited to simple applications, but to understand XMLHttpRequest.

If you can consider a variety of ready state - and understand the difference between these ready states in different browsers - you can quickly debug the application. You can even develop some creative features based on ready-to-state and return the request to the user and the customer. If you want to control the status code, you can set the application to handle script errors, non-expected responses, and edge conditions. The result is that the application can work normally at all times, not just everything can be running normally. Increase this ability to generate the HEAD request, check if a URL exists, and confirming that a file is modified, so that users can get a valid page, the information seen by the user is the latest, (most Important) Let them surprised how this app is robust and universal.

The purpose of this article is not to make your app look very gorgeous, but to help you remove the beauty of the text after the yellow spotlight, or the appearance is more like a desktop. Although these are the function of AJAX (introduced in several articles), they are like a cream on the surface of the cake. If you can use AJAX to build a solid foundation, let your app can handle errors and problems well, users return your site and application. In the next article, we will add this intuitive skill, which will make customers excited to shake. (Seriously, you must not want to miss the next article!)

转载请注明原文地址:https://www.9cbs.com/read-131740.html

New Post(0)