In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the knowledge points of the Ajax request object". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the knowledge points of the Ajax request object".
Learn more about HTTP ready state
ReadyState property of the XMLHttpRequest object: this property ensures that the server has completed a request and usually uses a callback function to read data from the server to update the contents of the Web form or page. Listing 1 shows a simple example:
Listing 1. Handle the response of the server 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") [xss_clean] = response [1]. Replace (/\ nrequest.responseText.split g, ");} 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:
0: the request is not initialized (open () has not been 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 obtained from the response). 3: the request is being processed; usually some data is available in the response, but the server has not finished generating the response. 4: the response is complete; you can get and use the server's response.
Secret ready state
The first ready state is characterized by a readyState attribute of 0 (readyState = = 0), which indicates an uninitialized state. * * once open () is called 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 a state of readyState = = 0. In addition, an uninitialized ready state is of no real use in a real application.
To satisfy our interest, however, see listing 2, which shows how to get this ready state when readyState is set to 0.
Listing 2. Get 0 ready state
Function getSalesData () {/ / create a request object createRequest (); alert ("Ready state is:" + request.readyState); / / start (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 that the Web page calls to initiate a request, such as when a button is clicked. Note that you must check the ready state before calling open (). Figure 1 shows the results of running this application.
Figure 1. Ready state 0
Obviously, this doesn't do you much good; there are very few cases where you need to make sure that the open () function has not been called. In most real situations of Ajax programming, the only use of this ready state is to generate multiple requests between functions using the same XMLHttpRequest object. In this (uncommon) case, you may want to make sure that the request 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 a typical request and response in turn before ending in the form of ready state 4. This is why you can see the line of if (request.readyState = = 4) in most callback functions; it ensures that the server has finished processing the request and is now safe to update the Web page or act on the data returned from the server.
The process of seeing this state happening is very simple. If the ready state is 4, we not only run the code in the callback function, but also output the ready state each time the callback function is called. Listing 3 shows an example of implementing this functionality.
Listing 3. View ready statu
Function updatePage () {/ / output current status alert ("updatePage () called with ready state of" + request.readyState);}
When 0 equals 4
When multiple JavaScript functions use the same request object, you need to check the ready state 0 to ensure that the request object is not in use, which can cause problems. Because readyState = = 4 represents a completed request, you will often find that request objects in the ready state that are not currently in use are still set to 4-- this is 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 resets the request object, but this function is not really used for this purpose. If you must use multiple functions, it is best to create and use one function for each function, rather than sharing the same object among multiple functions.
If you are not sure how to run this function, you need to create a function, then call it in the Web page and have it send a request to the server-side component (such as the function given in listing 2, or the examples given in parts 1 and 2 of this series). Make sure that the callback function is set to updatePage () when the request is made; to achieve this, you can set the onreadystatechange property of the request object to updatePage ().
This code is an exact demonstration of the meaning of onreadystatechange-every time the ready state of the request changes, updatePage () is called, and then we can see a warning.
Figure 2. Ready state 1
You can try to run this code yourself. Place it in the Web page and activate the event handler (click the button, press the tab key to switch focus between fields, or use any method you set to trigger the request). This callback function runs several times-- each time the ready state changes-- and you can see the warning for each ready state. This is the best way to track the stages of the request.
Browser inconsistencies
After you have a basic understanding of this process, try visiting your page from several different browsers. You should notice that how browsers handle these ready states are not consistent. For example, in Firefox 1.5, you will see the following ready states:
1.234
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 see-- something interesting. Here is the status seen in Safari 2.0.1:
2.34
Safari actually discards the first ready state, and there's no obvious reason for doing so; but that's how Safari works. This also illustrates an important point: although it is a good idea to ensure that the status of the request is 4 before using the data on the server, but code written depending on each transition ready state does get different results on different browsers.
For example, when using Opera 8.5, the displayed ready state is even worse:
3. 4
Finally, Internet Explorer displays the following status:
1.234
If you have a problem with the request, this is the first place to find the problem. The best way is to test both Internet Explorer and Firefox-- you'll see all four states, and you can check what each state of the request is in.
Next, let's take a look at the situation on the response side.
Response data under microscope
Once we understand the various ready states that occur during the request, we can take a look at another aspect of the XMLHttpRequest object-the responseText property. If you recall what we introduced in the previous article, you can see that this property is used to get data from the server. Once the server has finished processing the request, it can put any data needed to respond to the request data into the requested responseText. The callback function can then use this data, as shown in listings 1 and 4.
Listing 4. Use 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 all check the ready state at the beginning and get the value of the responseText property.
View the response text of the request
Similar to the ready state, the value of the responseText property changes throughout the life cycle of the request. To see this change, use the code shown in listing 5 to test the response text of the request 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 response text of'" + request.responseText + "'");}
Now open the Web application in your 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 ready states during the request. For example, in ready state 2, there is no responseText defined; if the JavaScript console is also open, you will see an error.
Figure 3. Response text with a ready state of 2
However, in ready state 3, the server has put a value in the responseText property, at least in this case
Figure 4. Response text with a ready state of 3
You will see that responses with a ready state of 3 vary from script to server and even from browser to browser. However, this is still very useful in debugging applications.
Get security data
All documents and specifications emphasize that data is safe to use only when the ready state is 4. Trust me, when the ready state is 3, you rarely find situations where you can't get data from the responseText property. However, it's not a good idea to rely on ready state 3 for your logic in your application-once you write code that relies on complete data for ready state 3, you're almost responsible for the incomplete data at that time.
It is better to provide some feedback to the user that there will be a quick response when you are in ready state 3. Although it's obviously not a good idea to use a function such as alert ()-- it's obviously wrong to use Ajax and then use a warning dialog to block users-- you can update fields in the form or page when the ready state changes. For example, for ready state 1, set the width of the progress indicator to 25%, for ready state 2, set the width of progress indicator to 50%, for ready state 3, set the width of progress indicator to 75%. Set the width of the progress indicator to 100% (complete) when the ready state is 4.
Of course, as you've already seen, this approach is very clever, but it depends on the browser. You will never see the first two ready states on Opera, and there is no first (1) on Safari. For this reason, I left this code as an exercise and did not include it in this article.
In-depth understanding of HTTP status codes
With the ready state and the server response you learned in Ajax programming techniques, you can add another level of complexity to your Ajax application-- using HTTP status codes. This code is nothing new to Ajax. They have existed since Web appeared. You may have seen several status codes in your Web browser:
401: unauthorized 403: forbidden 404: not found
You can find more status codes.
The value of xmlhttp.readyState and its explanation: 0: the request is not initialized (open () has not been 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 obtained from the response). 3: the request is being processed; usually some data is available in the response, but the server has not finished generating the response. 4: the response is complete; you can get and use the server's response.
The value and explanation of xmlhttp.status: 100mi-the customer must continue to issue the request 101m-the client requires the server to convert the HTTP protocol version according to the request
200Muk-transaction succeeded 201Mel-prompt to know that the URL202-- acceptance and processing of the new file is not completed, but the processing is not completed-the return information is uncertain or incomplete-the request has been received, but the return message is empty 205murf-the server has completed the request, the user agent must reset the currently browsed file 206mure-the server has completed some users' GET requests
The requested resource can be obtained in more than one place-delete the request data 302Mel-request data 303Mub has been found at other address-it is suggested that the client visit other URL or access mode 304Mel-the client has executed GET, but the file remains unchanged-the requested resource must get 306murf from the address specified by the server-the code used in the previous version of HTTP The temporary deletion of the requested resources is no longer used in the current version.
400Muk-error request, such as syntax error 401MUR-request authorization failed 402MUBE-keep valid ChargeToheader response 403Mub-request does not allow 404Mul-No file, query, or method defined by URl405-- user in Request-Line field does not allow 406Muk-according to the Accept sent by the user, the requested resource is not accessible-similar to 401 The user must first be authorized on the proxy server-the client did not complete the request 409 color within the hungry time specified by the user-to the current resource status The request cannot be completed-the resource is no longer available on the server and there is no further reference address 411muri-the server rejects the user-defined Content-Length attribute request 412Muk-one or more request header fields have error 413murf in the current request-the requested resource is larger than the size allowed by the server-the requested resource URL is longer than the length allowed by the server-the request resource does not support the request item Directory format 416 color-the request contains the Range request header field There is no range indication value within the scope of the current request resource, and the request does not contain the If-Range request header field 417-the server does not meet the expected value specified in the request Expect header field. If it is a proxy server, it may be that the next-level server cannot meet the request.
The server is temporarily unavailable, sometimes in order to prevent the system overload 503mura-the server overload or suspend maintenance of the 504murf-gate overload, the server uses another gate or service to respond to the user, the waiting time setting value is too long 505murf-the server does not support or reject the HTTP version specified in the request header.
1xx: information response class, indicating receiving the request and continuing to process 2xx: processing the successful response class, indicating that the action was successfully received, understood, and accepted 3xx: redirecting the response class, in order to complete the specified action, you must accept further processing 4xx: client error, client request contains syntax error or incorrect execution of 5xx: server error, server can not execute a correct request correctly
Explanation of xmlhttp.readyState4 & & xmlhttp.status200: request completed and returned successfully
To add an additional layer of control and response (and more robust error handling) to your Ajax application, you need to look at the status codes in the request and response appropriately.
200: everything is fine
In many Ajax applications, you will see a callback function that checks the ready state and then continues to leverage 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") [xss_clean] = response [1] .replace (/\ nCPG, ");}}
This proves to be a short-sighted and wrong approach to 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 answers the request, the ready state is set to 4 (even if the answer is not what the request expects). In the end, the user does not get valid data, and serious errors may occur when JavaScript tries to use server data that does not exist.
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 through the status property 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") [xss_clean] = response [1]. Replace (/\ nrequest.responseText.split g, ");} else alert (" status is "+ request.status) }}
By adding these lines of code, you can confirm that there is a problem, and the user will see a useful error message, not just a page of out-of-context data without any explanation.
Redirect and reroute
Before delving into errors, it's important to discuss an issue that you don't need to care about when using Ajax-- redirection. In the HTTP status code, this is the status code for the 300 series, including:
Permanent mobile 302: found (request redirected to another URL/URI) 305: use proxy (request must use a proxy to access the requested resource)
Ajax programmers may not care much about redirection for two reasons:
1. First of all, Ajax applications are usually written for a specific server-side script, servlet, or application. Ajax programmers don't know much about components that disappear without seeing them. So sometimes you know that the resource has moved (because you moved it, or by some means), and the next step is to modify the URL in the request and will not encounter this result again.
2. A more important reason is that Ajax applications and requests are encapsulated in sandboxie. This means that the domain that provides the Web page that generates Ajax requests 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 running on amazon.com; Ajax applications on ibm.com cannot make requests for 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 don't get the status code at all. A JavaScript error is usually generated in the debugging console. Therefore, after giving full consideration to the status code, you can completely ignore the problem of redirecting code.
Error
Once you receive the status code 200 and realize that you can largely ignore the 300 series status code, the only set of codes you need to worry about is the 400 series code, which illustrates different types of errors. Take a look back at listing 7 and notice that when handling errors, only a few common error messages are output to the user. Although this is a step in the right direction, these messages are still of little use in telling users and programmers what's wrong with application development.
First, we need to add support for pages that cannot be found. This should not actually happen in most production systems, but it is not uncommon when the location of the test script changes or when the programmer enters the wrong URL. If you can report 404 errors naturally, you can provide more help to 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.
Figure 5. Common error handling
Boundary situation and difficult situation
Seeing now, some novice programmers may wonder what this is really about. One thing you need to know is that less than 5% of Ajax requests require ready states such as 2 and 3 and status codes such as 403 (in fact, this ratio may be closer to 1% or less). These situations are very important, called boundary cases (edge case)-they only occur in very special situations, in which the strangest problems are encountered. Although these situations are not common, these boundary conditions account for 80% of the problems encountered by most users!
For the typical user, the fact that the application works 100 times is often forgotten, but once the application goes wrong, it will be clearly remembered by them. If you can handle boundary situations (or difficult situations) well, you can provide satisfactory returns for users who visit the site again.
The user cannot tell whether the problem is an authentication problem, a script not found (as is the case here), a user error, or something in the code that is causing the problem. Adding some simple code can make this error more specific. Refer to listing 8, which handles scripts that are not found or authentication errors, and gives specific messages 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") [xss_clean] = response [1] .replace (/\ nrequest.responseText.split 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 error as figure 5, but this time the error handling code better illustrates what happened to the user or programmer.
Figure 6. Special error handling
In our own application, consider clearing the user name and password in the event of an authentication failure and adding an error message to the screen. We can use a similar approach to better handle missing scripts or other 400 types of errors (for example, 405 indicates that unacceptable request methods such as sending HEAD requests are not allowed, while 407 indicates that proxy authentication is required). Whichever option is adopted, however, you need to start with the status code returned on the server.
Other request types
If you really want to control the XMLHttpRequest object, you can consider finally implementing this functionality-- adding the HEAD request to the instruction. In the previous two articles, we have shown how to generate GET requests; in a forthcoming article, you will learn about using POST requests to send data to the server. However, in the spirit of enhancing error handling and information collection, you should learn how to generate HEAD requests.
Generate request
Generating a HEAD request is actually very simple; you can call the open () method with "HEAD" (instead of "GET" or "POST") as the first parameter, 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 in this way, the server does not return a real response as it did for a GET or POST request. Instead, the server only returns the header of the resource, which includes when the content in the response was last modified, whether the requested resource exists, and a lot of other useful information. You can use this information to learn about resources before the server processes and returns them.
The easiest thing you can do for such a request is simply output the contents of all the response headers. This gives you an idea of what can be used through HEAD requests. 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 ());}}
Check URL
You have seen how to check for 404 errors when URL does not exist. If this becomes a common problem-- perhaps a specific script or servlet is missing-- then you may want to check the URL before generating a complete GET or POST request. To do this, generate a HEAD request and then check for 404 errors in the callback function; listing 11 shows 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);}
To be honest, this code is not very valuable. The server must respond to the request and construct a response header to fill the length of the content, so it does not save any processing time. In addition, this takes as much time as it takes to generate a request and use a HEAD request to see if URL exists, because it generates a request that uses GET or POST, rather than just handling the error code as shown in listing 7. However, sometimes it's useful to know exactly what's available; you never know when creativity will burst out or when you need an HEAD request!
Useful HEAD request
One area where you will find HEAD requests very useful is to view the length or type of content. This determines whether a large amount of data needs to be sent back to process the request, and whether the server tries to return binary data instead of HTML, text, or XML (all three types of data are easier to handle in JavaScript).
In these cases, you only use the appropriate header name and pass it to the getResponseHeader () method of the XMLHttpRequest object. Therefore:
To get the length of the response, simply 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 cause the request to slow down (by forcing an HEAD request to get data about the response, and then using an GET or POST request to actually get the response). However, in situations where you are not sure about scripts or server-side components, using HEAD requests can get some basic data without actually processing the response data or requiring a large amount of bandwidth to send the response.
Thank you for your reading, the above is the content of "what are the knowledge points of the Ajax request object". After the study of this article, I believe you have a deeper understanding of what the knowledge points of the Ajax request object have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.