This article discusses the problems related to readyState and status in Ajax, ajaxreadystate.
Let's take a look at the following code, and then introduce in detail the readyState and status issues in Ajax. The details are as follows:
Var getXmlHttpRequest = function () {try {// the XMLHttpRequest object return new XMLHttpRequest ();} catch (e) {// The earlier version of IE does not provide the XMLHttpRequest object, IE6 or lower // you must use the specific implementation of the IE browser ActiveXObjectreturn new ActiveXObject ("Microsoft. XMLHTTP ") ;}}; var xhr = getXmlHttpRequest (); // readyState 0 => initialize 1 => load 2 => load complete 3 => resolution 4 => complete // console. log (xhr. readyState); 0xhr. open ("TYPE", "URL", true); // console. log (xhr. readyState); 1xhr. send (); // console. log (xhr. readyState); 1xhr. onreadystatechange = function () {// console. log (xhr. status); // HTTP status? // console. log (xhr. readyState); 2 3 4if (xhr. readyState === 4 & xhr. status = 200) {alert (xhr. responseText );}};
1. Ajax: differences between readyState and status
ReadyState refers to several States that have been used to run AJAX. no matter whether the access is successful or not, the response steps can be understood as AJAX running steps, obtained by using "ajax. readyState"
Status indicates that no matter whether AJAX access is successful, the HTTP header information code returned by the server is obtained by the HTTP protocol based on the submitted information.
Overall understanding: state represents an overall state. The status is a specific small state under this large state.
2. 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.
0: initialization. the XMLHttpRequest object has not been fully initialized.
1: load, XMLHttpRequest object starts sending requests
2: loading is complete. The XMLHttpRequest object request is sent completely.
3: parse the XMLHttpRequest object to start reading the Server Response
4: finished. The XMLHttpRequest object reads the server and the response ends.
3. 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.
1xx: Information Response class, indicating that the request is received and processed continuously
2xx: Successful response class, indicating that the action is successfully received, understood, and accepted
3xx: redirect response class. To complete the specified action, you must accept further processing.
4xx: client error. The client request contains a syntax error or cannot be correctly executed.
5xx: server error. The server cannot correctly execute a correct request.
100 -- the customer must continue to send the request
101 -- the client requests the server to convert the HTTP protocol version according to the request
200 -- transaction successful
201 -- prompt to know the URL of the new file
202 -- accept and process, but not complete
203 -- the returned information is uncertain or incomplete
204 -- the request is received, but the returned information is null.
205 -- when the server completes the request, the user agent must reset the file that has been browsed.
206 -- the server has completed some users' GET requests
300 -- the requested resources can be obtained in multiple places
301 -- Delete request data
302 -- request data found at other addresses
303 -- we recommend that you access other URLs or access methods.
304 -- the client has executed GET, but the file has not changed
305 -- the requested resource must be obtained from the address specified by the server
306 -- code used in HTTP of the previous version, which is not used in the current version
307 -- declaring temporary deletion of requested resources
400 -- incorrect request, such as syntax error
401 -- authorization request failed
402 -- retain valid ChargeTo header response
403 -- the request is not allowed
404 -- no file, query, or URl found
405 -- the method defined in the Request-Line field is not allowed.
406 -- the requested resource is inaccessible due to the user's Accept drag.
407 -- similar to 401, the user must first be authorized on the Proxy Server
408 -- the client did not complete the request within the specified time
409 -- the request cannot be completed due to the current resource status
410 -- this resource is no longer available on the server and there is no further reference address
411 -- the server rejects the User-Defined Content-Length attribute request
412 -- one or more request header fields are incorrect in the current request
413 -- the requested resource is larger than the size allowed by the server
414 -- the requested resource URL is longer than the length allowed by the server
415 -- the requested resource does not support the format of the requested project
416 -- The request contains the Range request header field. There is no range indication value in the current request resource Range, and the request does not contain the If-Range request header field.
417 -- the server does not meet the expectation specified in the header field of the response CT request. If it is a proxy server, it may be that the next-level server cannot meet the request
500 -- Internal error occurred on the server
501 -- the server does not support the requested function
502 -- the server is temporarily unavailable, sometimes to prevent system overload
503 -- server overload or service suspension
504 -- the gateway is overloaded. The server uses another gateway or service to respond to the user. The waiting time is long.
505 -- the server does not support or reject the specified HTTP version in the Request Header
4. Thinking: Why should the onreadystatechange function be used to determine both readyState and status?
Method 1: Use readyState only
var getXmlHttpRequest = function () {if (window.XMLHttpRequest) {return new XMLHttpRequest();}else if (window.ActiveXObject) {return new ActiveXObject("Microsoft.XMLHTTP");}};var xhr = getXmlHttpRequest();xhr.open("get", "1.txt", true);xhr.send();xhr.onreadystatechange = function () {if (xhr.readyState === 4) {alert(xhr.responseText);}};
The service response failed, but still returned information. This is not the expected result.
If the returned result is not 200, but 404 or 500, because only readystate is used for judgment, the returned result is 200, 404, or 500. If the response is successful, execute the following javascript code, and the result will cause various unexpected errors. Therefore, it does not work if you only use readyState.
Method 2: only use status to judge
var getXmlHttpRequest = function () {try{return new XMLHttpRequest();}catch(e){return new ActiveXObject("Microsoft.XMLHTTP");}};var xhr = getXmlHttpRequest();xhr.open("get", "1.txt", true);xhr.send();xhr.onreadystatechange = function () {if (xhr.status === 200) {alert("readyState=" + xhr.readyState + xhr.responseText);}};
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 = 3" window, and the third is the "readyState = 4" window. Therefore, the onreadystatechange function is triggered not only when the readyState is changed to 4, but every change of readyState (2, 3, 4, so there is the situation we mentioned above. It can be seen that it is not feasible to use status alone.
5. From the above test, we can know that the readyState and status are indispensable during the 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 test, we know that every change to readyState triggers the onreadystatechange function. If you first judge the status, the status will be judged once more. Although the performance has little impact, we should keep the readyState judgment in front of the idea of pursuing the ultimate code.
xhr.readyState === 4 && xhr.status === 200
The above section describes the readyState and status in Ajax. I hope it will be helpful to you, if you have any questions, please leave a message and the editor will reply to you in time. Thank you very much for your support for the help House website!