Home >Web Front-end >JS Tutorial >What are the differences between using readyState and status in Ajax?

What are the differences between using readyState and status in Ajax?

php中世界最好的语言
php中世界最好的语言Original
2018-04-02 10:06:201726browse

This time I will bring you what are the differences between using readyState and status in Ajax, what are the precautions when using readyState and status in Ajax, the following is a practical case, let's take a look.

In the previous articles, I analyzed jquery’s ajax asynchrony and synchronization, as well as some exception handling. I feel that the readyState and status of ajax have not been explained clearly. Today, let’s talk about the ajax status.

jquery ajax function source code is like this:

var getXmlHttpRequest = function () {
  if (window.XMLHttpRequest) {
    //主流浏览器提供了XMLHttpRequest对象
    return new XMLHttpRequest();
  }
  else if (window.ActiveXObject) {
    //低版本的IE浏览器没有提供XMLHttpRequest对象
    //所以必须使用IE浏览器的特定实现ActiveXObject
    return new ActiveXObject("Microsoft.XMLHTTP");
  }
};
var xhr = getXmlHttpRequest();
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    //获取成功后执行操作
    //数据在xhr.responseText
  }
};
xhr.open("TYPE", "URL", true);
xhr.send("");

What is readyState

readyState is an attribute of the XMLHttpRequest object , used to identify the state of the current XMLHttpRequest object.

ReadyState has a total of 5 state values, ranging from 0 to 4. Each value represents a different meaning, as shown in the following table:

0 Uninitialized state: At this time, it has been created An XMLHttpRequest object

1 Ready to send 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 Already sent status : At this time, a request has been sent to the server through the send method, but a response has not been received

3 Receiving status: At this time, the HTTP response header information has been received, but the message body part Not yet fully received

4 Complete response status: At this time, the reception of the HTTP response has been completed

What is status

Status is an attribute of the XMLHttpRequest object, indicating the HTTP status code of 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, the 101 status code means that the server will notify the client to use a higher version of the HTTP protocol.

2XX The request was successful. For example, a 200 status code indicates that the response header or data body expected by the request will be returned with this response.

3XX Redirect. For example, the 302 status code 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, the 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 situation that prevented it from completing the response. Generally speaking, this problem will occur when an error occurs in the program code.

Throw question

Why does the function implementation of onreadystatechange need to determine readyState and status at the same time?

We know that readyState === 4 has already indicated that the request response was successful, why do we need subsequent status? With questions in mind, let’s start doing some experiments.

Only use readyState to judge

The implementation code of javascript 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("");

We throw an exception on the server side:

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

When running the javascript code, the prompt window appears as follows:

The service response has an error, but the information is still returned. This is not the result we want. . Open Fiddler monitoring, you can see that data.aspx returns a 500 response, but because it only uses readystate to make judgments, it does not care whether the returned result is 500 or 200. As long as the response is returned successfully, the next javascript code will be executed. The result will be various unpredictable errors. So just using readyState to judge will not work.

Thinking about it from another perspective, if the status code returns 200, it means that the response is successful. So, can we not use readyState and only use status to make judgments? Okay, with questions in mind, let’s continue the experiment.

Only use status to judge

The code on the javascript side 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("");

事实上,结果却不像预期那样。响应码确实是返回了200,但是总共弹出了3次窗口!第一次是“readyState=2”的窗口,第二次是“readyState=3Test”的窗口,第三次是“readyState=4Test”的窗口。由此,可见onreadystatechange函数的执行不是只在readyState变为4的时候触发的,而是readyState的每次变化都会触发,所以就出现了前面说的那种情况。可见,单独使用status判断也是行不通的。

进一步思考

  由上面的试验,我们可以知道判断的时候readyState和status缺一不可。那么readyState和status的先后判断顺序会不会有影响呢?我们可以将status调到前面先判断,代码如 xhr.status === 200 && xhr.readyState === 4。

  事实上,这对于最终的结果是没有影响的,但是中间的性能就不同了。由上一个试验我们知道,readyState的每次变化都会触发onreadystatechange函数,假如先判断status,那么每次都会多判断一次status的状态。虽然性能上影响甚微,不过我们还是应该抱着追求极致代码的想法,把readyState的判断放在前面。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

jQuery+Ajax判断输入的验证码是否通过

Ajax怎么做出智能搜索框的提示功能

The above is the detailed content of What are the differences between using readyState and status in Ajax?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn