Discuss the problem _ajax related to readystate (status value) and status (status code) in Ajax

Source: Internet
Author: User
Tags response code

First look at the following code, and then give you a detailed description of Ajax in the ReadyState (status value) and status (status code) issues, the specific content as follows:

var getxmlhttprequest = function () {
//main browser provides XMLHttpRequest object return
new XMLHttpRequest ();
} catch (E) {
//low version of IE browser does not provide XMLHttpRequest object, IE6
below//So must use IE browser specific implementation activexobject return
new ActiveXObject ("Microsoft.XMLHTTP");
var xhr = Getxmlhttprequest ();
ReadyState 0=> initialization 1=> load 2=> load Complete 3=> resolution 4=> (
Console.log); 0
xhr.readystate (" TYPE "," URL ", true);
Console.log (xhr.readystate); 1
xhr.send ();
Console.log (xhr.readystate); 1
xhr.onreadystatechange = function () {
//Console.log (xhr.status);//http status
//Console.log ( Xhr.readystate); 2 3 4
if (xhr.readystate = 4 && Xhr.status = =) {
alert (xhr.responsetext);

difference between 1.ajax:readystate (status value) and status (status code)

ReadyState, refers to the number of States running AJAX experience, regardless of whether the success of the access will respond to the steps, can be understood to become Ajax run steps, using "Ajax.readystate" to obtain

Status, refers to whether the Ajax access is successful, by the HTTP protocol based on the information submitted, the server returned the HTTP header information code, using "Ajax.status" to obtain
General understanding: It is simple to understand that State represents a whole. And the status is the small state below the big one.

2. 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 a different meaning

0: Initialization, XMLHttpRequest object has not yet completed initialization

1: Load, XMLHttpRequest object starts sending request

2: Load complete, XMLHttpRequest object's request send complete

3: Parsing, the XMLHttpRequest object starts reading the server's response

4: Complete, XMLHttpRequest object Read server response end

3. 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 code can be divided into 5 categories in total

1XX: Information response class, which indicates receipt of a request and continues processing

2XX: Handling a successful response class, indicating that the action was successfully received, understood, and accepted

3XX: Redirect Response class, in order to complete the specified action, you must accept further processing

4XX: Client error, customer request contains syntax error or is not properly executed

5XX: Service-side error, server does not perform a correct request correctly

100--customer must continue to issue a request

101--client requires the server to convert the HTTP protocol version on request

200--Trading Success

201--prompts to know the URL of the new file

202--accept and process, but processing incomplete

203--return information is uncertain or incomplete

204--request received, but return information is empty

The 205--server completes the request and the user agent must reset the files that are currently browsed

The 206--server has completed some of the user's Get requests

300--requested resources can be obtained in multiple places

301--Delete request data

302--found request data at other addresses

303--advises customers to access other URLs or access methods

The 304--client has executed a GET, but the file has not changed

The resource requested by 305--must be obtained from the address specified by the server

306--the code used in the previous version of HTTP, which is no longer used in the current version

307--declare the requested resource to be temporarily deleted

400--error requests, such as syntax errors

401--Request Authorization failed

402--retains a valid Chargeto header response

403--Request not allowed

404--found no files, queries, or URLs

405--the method defined by the user in the Request-line field does not allow

406--requests for resources to be inaccessible based on accept drag sent by the user

407--is similar to 401, the user must first be authorized on the proxy server

The 408--client did not complete the request within the time specified by the user

409--the current resource state, the request cannot be completed

This resource is no longer available on the 410--server and there is no further reference address

411--server rejects user-defined Content-length property request

412--one or more request header fields errors in the current request

413--requested resource is greater than the size allowed by the server

414--The requested resource URL is longer than the length allowed by the server

Request item format not supported by 415--request Resource

The 416--request contains a range request header field, there is no range indicating value within the current request resource range, and the request does not contain a If-range request header field

417--server does not meet the expected value specified by the request Expect header field, if it is a proxy server, it may be that the next level of server does not meet the request

500--Server generates internal error

The requested function is not supported by the 501--server

502--servers are temporarily unavailable, sometimes to prevent system overload

503--server overload or suspend repair

504--Gateway overload, the server to use another gateway or service to respond to users, waiting time to set a longer value

505--server does not support or reject the HTTP version specified in the Support request header

4. Thinking question : Why do onReadyStateChange's function implementations have to judge both readystate and status at the same time?

The first way to think: Use only readystate

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 was wrong, but it returned the information, which is not the result we wanted.

If the return is not 200, but 404 or 500, it ignores the return result of 200, 404, or 500, as long as the response returns successfully, executes the next JavaScript code, resulting in unexpected errors. So just using readystate to judge is not workable.

The second way of thinking: use only status judgments

var getxmlhttprequest = function () {
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 = =) {
alert ("readystate=" + xhr.readystate + xhr.resp Onsetext);

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=3" window, the third time is "readystate=4" window. Thus, the performance of the visible onreadystatechange function is not triggered only when the readystate changes to 4, but readystate (2, 3, 4) each time the change is triggered, so there is the situation mentioned above. It can be seen that using the status judge alone is not workable.

5. From the above test, we can know when the judge 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 judge, 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. We know from the test that every change in readystate triggers the onreadystatechange function, and if you judge status first, then you will judge the status of a status more than once. Although the performance of the impact of very little, but still should embrace the idea of the ultimate code, put the readystate judgment in front.

Xhr.readystate = = 4 && xhr.status = = 200

The above is a small set to introduce the discussion of Ajax about readystate (status value) and status (status code) of the problem, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.