Programmers familiar with web development must be familiar with Ajax. Now many JS frameworks have encapsulated Ajax implementations, such as jquery's Ajax functions, which are very convenient to call. Of course, this article does not describe the use of the framework. We will start with the JavaScript source code implementation of Ajax.
Ajax source code implementation
VaR getxmlhttprequest = function () {If (window. XMLHttpRequest) {// the XMLHTTPRequest object return New XMLHttpRequest ();} else if (window. activexobject) {// The earlier version of IE does not provide the XMLHTTPRequest object // you must use the specific implementation of the IE browser activexobject return New activexobject ("Microsoft. XMLHTTP ") ;}}; var xhr = getxmlhttprequest (); xhr. onreadystatechange = function () {If (xhr. readystate === 4 & xhr. status = 200) {// after obtaining the information, perform the operation // the data is stored in xhr. responsetext }}; xhr. open ("type", "url", true); xhr. send ("");
We can see that the xhr object monitors the final completion of Ajax through onreadystatechange. Here we also welcome the main characters to be discussed: readystate and status.
What is readystate?
Readystate is an attribute of the XMLHTTPRequest object, used to identify the status of the current XMLHTTPRequest object.
Readystate has a total of five Status values, 0 ~ 4. Each value represents a different meaning, as shown in the following table:
0 |
Uninitialized status: An XMLHTTPRequest object has been created. |
1 |
Prepare the sending status: At this time, the open method of the XMLHTTPRequest object has been called, and the XMLHTTPRequest object is ready to send a request to the server. |
2 |
Sent status: At this time, a request has been sent to the server through the send method, but no response has been received |
3 |
Receiving status: At this time, the HTTP response header information has been received, but the message body has not completely received |
4 |
Response status: At this time, the HTTP response has been received. |
What is status?
Status is an attribute of the XMLHTTPRequest object, indicating the HTTP status code of the response.
Under http1.1, HTTP status codes can be divided into five categories, as shown in the following table:
1xx |
The server must continue to process the request. For example, the 101 Status Code indicates that the server will notify the client to use a later version of HTTP protocol. |
2XX |
The request is successful. For example, the 200 Status Code indicates that the request's desired response header or data body will be returned with this response. |
3xx |
Redirection. For example, the 302 status code indicates temporary redirection. 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, Status Code 404 indicates that the resource requested by the client does not exist. |
5xx |
Server error. For example, the 500 Status Code indicates that the server encountered an unexpected situation, which caused it to fail to respond. Generally, this problem occurs when the program code fails. |
Throw a problem
Why should the onreadystatechange function be used to determine both readystate and status?
We know that readystate = 4 indicates that the request response is successful. Why do we need the subsequent status? Let's start experimenting with the problem.
Only use readystate to judge
The javascript implementation code 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 uses the ASP. NET webform framework. Now we have some hands and feet on data. aspx in the background. Let's try it to report an error! C # The 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 and the prompt window displays the following:
The service response failed, but still returned information, which is not the expected result. Enable fiddler monitoring and you can see data. aspx returns a 500 response, but because it only uses readystate for judgment, it ignores whether the returned result is 500 or 200. As long as the response is returned successfully, the following JavaScript code is executed, the results may cause unexpected errors. Therefore, it does not work if you only use readystate.
From another perspective, if the status code 200 is returned, the response is successful. Can I use status alone instead of readystate? Okay. Let's continue the experiment with questions.
Only use status to judge
The javascript 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 === 200) { alert("readyState=" + xhr.readyState + xhr.responseText); }};xhr.open("GET", "/data.aspx", true);xhr.send("");
This operation will be performed in the Data. aspx background so that it returns only one string, 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 true that a prompt box containing a string containing "readystate = 4 test" is displayed? Run it. The result is not far from us!
In fact, the results are not as expected. The response code returns 200, but a total of three windows are displayed! The first is the "readystate = 2" window, the second is the "readystate = 3test" window, and the third is the "readystate = 4test" window. As a result, we can see that the onreadystatechange function is not triggered only when the readystate is changed to 4, but every change to the readystate will be triggered, so the situation described above appears. It can be seen that it is not feasible to use status alone.
Further consideration
From the above test, we can know that the readystate and status are indispensable at the time of judgment. So will the order of readystate and status be affected? We can adjust the status to the previous one to determine the Code, such as xhr. Status = 200 & xhr. readystate = 4.
In fact, this does not affect the final result, but the intermediate performance is different. From the previous test, we know that every change in readystate triggers the onreadystatechange function. If the status is first determined, The status will be determined once more. Although the performance has little impact, we should hold the idea of pursuing the ultimate code and put the readystate judgment in front.
If you have a new idea, leave a message to discuss it.
References:Sharp jquery, HTTP status code Wikipedia