Reprint: Ajax discussion on readystate and status

Source: Internet
Author: User
Tags response code

Reprint: Ajax discussion on readystate and status

Http://www.cnblogs.com/teroy/p/3917439.html

Programmers who are familiar with web development must not be unfamiliar with Ajax. There are now many JS frameworks that encapsulate Ajax implementations, such as JQuery's Ajax functions, which are very handy to call. Of course this article does not intend to talk about the use of the framework, we will start from the Ajax JavaScript source implementation.

Ajax Source Code Implementation
var getxmlhttprequest =function() {If(Window. XMLHttpRequest) {//XMLHttpRequest objects are available in mainstream browsersReturnNewXMLHttpRequest (); }ElseIf(Window. ActiveXObject) {//The XMLHttpRequest object is not available in the lower version of IE browser// so you must use the specific implementation of IE browser activexobject return new ActiveXObject ("Microsoft.XMLHTTP" var xhr = Getxmlhttprequest (); xhr.onreadystatechange = functionif ( Xhr.readystate = = = 4 && Xhr.status = = = 200//< Span style= "color: #008000;" > Execute operation // data in Xhr.responsetext}};xhr.open ("TYPE", "URL", true  

You can see that the XHR object is through onreadystatechange to listen to the final completion of Ajax, here also ushered in the main role to be discussed: readystate and status.

What is readystate

ReadyState is a property of the XMLHttpRequest object that identifies what state the current XMLHttpRequest object is in.

ReadyState a total of 5 status values, respectively, 0~4, each value represents a different meaning, as shown in the following table:

  0     uninitialized state: At this point, a XMLHttpRequest object has been created
  1 &nbs p; Prepare Send status: At this point, the open method of the XMLHttpRequest object has been called, and the XMLHttpRequest object is ready to send a request to the server-side
  2   sent status: At this point, a request has been sent to the server by the Send method, but no response has been received
  3   is receiving status: HTTP response header information has been received, but the message body part has not yet fully received the
  4   Complete the Response status: The HTTP response has already been received
What is status

Status is a property of the XMLHttpRequest object that represents the HTTP status code for the response.

Under the HTTP1.1 protocol, HTTP status codes can be divided into 5 categories, as shown in the following table:

1XX The server receives the request and needs to continue processing. For example, a 101 status code indicates that the server will notify the client to use a later version of the HTTP protocol.
2XX The request was successful. For example, a 200 status code indicates that the desired response header or data body of the request will be returned with this response.
3XX redirect. For example, a 302 status code, which indicates a temporary redirect, the request will contain a new URL address, and the client will make a GET request for the new address.
4XX Client error. For example, a 404 status code indicates that the resource requested by the client does not exist.
5XX Server error. For example, a 500 status code indicates that the server encountered an unexpected condition that caused it to fail to complete the response, which generally occurs when the code of the program is faulted.
Throw a question

Why should the function of onreadystatechange be judged readystate and status at the same time?

We know readyState = = 4 has indicated that the request has been successfully responded to, why do you want to follow the status? With questions, let's start experimenting.

Only use readystate to judge

The implementation code for the JavaScript side is as follows:

var getxmlhttprequest =function() {If window. XMLHttpRequest) {return new XMLHttpRequest (); } else if window. ActiveXObject) {return new ActiveXObject (" Microsoft.XMLHTTP "); }}; var xhr = Getxmlhttprequest (); xhr.onreadystatechange = functionif ( Xhr.readystate = = = 4true  

This demo uses the ASP. NET WebForm Framework, now we are in the background data.aspx do some hands and feet, rather let it error try! The C # code is as follows:

Class data:system.web.ui.page{    void Page_Load (objectnew Exception ("Error" ); }}

Running the JavaScript code, the prompt window appears as follows:

The service responded with an error, but returned the information, which is not the result we want. Turn on fiddler monitoring, You can see that data.aspx is returning a 500 response, but because it only uses readystate to judge, it ignores whether the returned result is 500 or 200, and as long as the response returns successfully, the next JavaScript code is executed, resulting in a variety of unpredictable errors. So only using readystate to judge is not feasible.

For another angle, the status code returns 200 to indicate that the response was successful, so is it possible not to use the readystate and only use status alone to judge? Well, take the question and continue with the experiment.

Use status only to judge

The JavaScript-side code is implemented as follows:

var getxmlhttprequest =function() {If(Window. XMLHttpRequest) {return newelse if window. ActiveXObject) {return new ActiveXObject (" Microsoft.XMLHTTP "); }}; var xhr = Getxmlhttprequest (); xhr.onreadystatechange = functionif ( Xhr.status = = = 200) {alert ("readystate=" + xhr.readystate +  Xhr.responsetext); }};xhr.open ("GET", "/data.aspx", true  

This time it will be processed in the background of data.aspx, so that it only returns a string, implemented as follows:

Class data:system.web.ui.page{    void Page_Load (object sender, EventArgs e) {Response.Write (  "Test"); Response.End (); }}

Everything is so natural, is not as long as the pop-up of a string that writes a line "readystate=4test" the Prompt box, that the result is set up? Run it up, the result is not far away from us!

In fact, the results were not as expected. The response code did return 200, but it popped a total of 3 windows! The first is "readystate=2" window, the second is "readystate=3test" window, the third time is "readystate=4test" window. Thus, it can be seen that the execution of the onreadystatechange function is not only triggered when the readystate becomes 4, but each change of the readystate is triggered, so there is a situation that is mentioned earlier. As you can see, using status alone is not a viable decision.

Further thinking

By the above experiment, we can know when to judge the readystate and status indispensable. Will the order of readystate and status be affected? We can put the status before the first judge, the code such as Xhr.status = = = && Xhr.readystate = = = 4.

In fact, this has no effect on the final result, but the performance in the middle is different. From the previous experiment we know that each change of readystate will trigger the onreadystatechange function, if the first judge status, then each time will judge the status of more than once. Although the performance of the impact is very little, but we should embrace the pursuit of extreme code ideas, the ReadyState judgment in front.

Reprint: Ajax discussion on readystate and status

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.