Ajax discussion on readystate and status

Source: Internet
Author: User
Tags object final header response code return string version window

Programmers who are familiar with web development must not be unfamiliar with Ajax. Now there are 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) {       //mainstream browsers provide XMLHttpRequest objects     
    return new XMLHttpRequest ();    }     else if window. ActiveXObject) {       //low version of IE browser does not provide XMLHttpRequest object         //So you must use the specific implementation of IE browser ActiveXObject         return new
ActiveXObject ("Microsoft.XMLHTTP");
   };
var xhr = Getxmlhttprequest (); Xhr.onreadystatechange = function () {    if (xhr.readystate = 4 && Xhr.status = =) { 
      //Obtain success after Operation        //data in Xhr.responsetext
   };
Xhr.open ("TYPE", "URL", true); Xhr.send (""); 

As you can see, the XHR object is to monitor the final completion of Ajax through onReadyStateChange, and here is the main character to be discussed: readystate and status.

What is readystate

ReadyState is an attribute of the XMLHttpRequest object that identifies what state the current XMLHttpRequest object is in.

ReadyState has a total of 5 state values, 0~4, each representing different meanings, as shown in the following table:

0 Uninitialized state: At this point, a XMLHttpRequest object has been created
1 Ready to send status: At this point, the XMLHttpRequest object's open method 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 via the Send method to the server side, but no response has been received
3 Receiving Status: HTTP response header information has been received at this time, but the message body part has not been fully received
4 Complete response Status: At this point, the HTTP response has been received

What is status

Status is an attribute of the XMLHttpRequest object that represents the HTTP status code of the response.

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

1XX The server received 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 response header or data body that the request expects will be returned with this response.
3XX redirect. For example, a 302 status code indicates a temporary redirect, the request will contain a new URL address, and the client will make a GET request to 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. A 500 status code, for example, indicates that the server encountered an unexpected situation that caused it to fail to complete the response, which typically occurs when the program code is wrong.

Throw a question

Why do onreadystatechange function implementations have to judge both readystate and status at the same time?

We know that readyState = = 4 has already indicated that the request response succeeded, why do we have to follow the status? With questions, let's start experimenting.

Use only 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 = function () {
if (xhr.readystate = = 4) {
alert (xhr.responsetext);
}
};
Xhr.open ("Get", "/data.aspx", true);
Xhr.send ("");

This demo demo uses asp.net webform frame, now we in the backstage data.aspx do some hands and feet, let it give an error to try! The C # code is as follows:

public partial class Data:System.Web.UI.Page
{
protected void Page_Load (object sender, EventArgs e)
{
throw new Exception ("Error");
}
}

Run the JavaScript code, prompting the window to appear as follows:

The service response was wrong, but it returned the information, which is not the result we wanted. Turn on fiddler monitoring, you can see Data.aspx return 500 response, but because only use readystate to judge, it ignores the return of the result is 500 or 200, as long as the response returned successfully, execute the next JavaScript code, The result will be a variety of unpredictable errors. So just using readystate to judge is not workable.

Another point of view, the status code returned 200 to indicate the success of the response, then can not use readystate, alone only use status to make judgments? Well, with the problem, go ahead and do the experiment.

Only use status to judge

The JavaScript-side code is implemented 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 = function () {
if (xhr.status = =) {
alert ("readystate=" + xhr.readystat    e + xhr.responsetext);
}
};
Xhr.open ("Get", "/data.aspx", true);
Xhr.send ("");

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

public partial class Data:System.Web.UI.Page
{
protected void Page_Load (object sender, EventArgs e)
{
Response.Write ("Test");
Response.End ();
}
}

Everything is so natural, is it just a pop-up box with a string of "readystate=4test" that says the result is set? 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 a total of 3 windows were popped! The first time is "readystate=2" window, the second is "readystate=3test" window, the third time is "readystate=4test" window. As a result, the visible onreadystatechange function is not only triggered when the readystate becomes 4, but readystate every change triggers, so there is a situation like the one described earlier. It can be seen that using the status judge alone is not workable.

Further thinking

From the above test, we can know when to judge the readystate and status is indispensable. So readystate and status of the sequence of judgment will have an impact? We can adjust the status to the front to determine 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 last test we know that every change in readystate triggers the onreadystatechange function, and if you judge the status first, you will judge the status of a status more than once. Although the performance of the impact is very little, but we should embrace the idea of the pursuit of the ultimate code, the readystate judgment on the front.



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.