Home > Web Front-end > JS Tutorial > body text

How to use readyState and status in Ajax

php中世界最好的语言
Release: 2018-04-04 11:33:16
Original
1950 people have browsed it

This time I will show you how to use readyState and status in Ajax. What are the precautions for using readyState and status in Ajax? The following is a practical case, let's take a look.

Let’s first look at the following piece of code, and then give you a detailed introduction to the issues related to readyState (status value) and status (status code) in Ajax. The specific content is as follows:

var getXmlHttpRequest = function () {
try{
//主流浏览器提供了XMLHttpRequest对象
return new XMLHttpRequest();
}catch(e){
//低版本的IE浏览器没有提供XMLHttpRequest对象,IE6以下
//所以必须使用IE浏览器的特定实现ActiveXObject
return new ActiveXObject("Microsoft.XMLHTTP");
}
};
var xhr = getXmlHttpRequest();
// readyState 0=>初始化 1=>载入 2=>载入完成 3=>解析 4=>完成
// console.log(xhr.readyState); 0
xhr.open("TYPE", "URL", true);
// console.log(xhr.readyState); 1
xhr.send();
// console.log(xhr.readyState); 1
xhr.onreadystatechange = function () {
// console.log(xhr.status); //HTTP状态吗
// console.log(xhr.readyState); 2 3 4
if(xhr.readyState === 4 && xhr.status === 200){
alert(xhr.responseText);
}
};
Copy after login

1.Ajax: The difference between readyState (status value) and status (status code)

readyState refers to several states experienced by running AJAX, regardless of access The steps that will respond if successful can be understood as AJAX running steps. Use "ajax.readyState" to obtain

status, which refers to the information returned by the server based on the submitted information by the HTTP protocol regardless of whether the AJAX access is successful or not.

HTTP header informationCode, use "ajax.status" to obtain Overall understanding: It can be simply understood that state represents an overall status. And status is the specific small status under this big state.

2. 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 status values, ranging from 0 to 4. Each value represents a different meaning

0: Initialization, the XMLHttpRequest object has not yet completed initialization

1: Loading, the XMLHttpRequest object starts to send the request

2: Loading is completed, the request of the XMLHttpRequest object is sent

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

4: Completed, the XMLHttpRequest object reads the server response and ends

3. What is status

status is an attribute of the XMLHttpRequest object.

HTTP status code indicating response

Under the HTTP1.1 protocol, HTTP status codes can be divided into 5 major categories

1xx: Information response type, indicating receipt Request and continue processing

2xx: Processing success response class, indicating that the action was successfully received, understood and accepted

3xx: Redirect response class, in order to complete the specified action, further processing must be accepted

4xx: Client error, the client request contains a

syntax error or cannot be executed correctly

5xx: Server error, the server cannot correctly execute a correct request

100——The client must continue to make the request

101——The client requires the server to convert the HTTP protocol version according to the request

200——The transaction is successful

201——Prompt Know the URL of the new file

202——Accepted and processed, but the processing was not completed

203——Return information is uncertain or incomplete

204——Request received , but the return information is empty

205——The server has completed the request, the user agent must reset the currently browsed files

206——The server has completed some users’ GET requests

300 - The requested resource is available in multiple locations

301 - Delete the request data

302 - The request data was found at another address

303 ——It is recommended that the client 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 the previous version of HTTP, no longer used in the current version

307 - Declaration that the requested resource is temporarily deleted

400 - Bad request , such as syntax error

401——Request authorization failed

402——Retain valid ChargeTo header response

403——Request not allowed

404—— — No file, query, or URL found

405 — The method defined by the user in the Request-Line field is not allowed

406 — According to the Accept drag sent by the user, the requested resource is not accessible

407——类似401,用户必须首先在代理服务器上得到授权

408——客户端没有在用户指定的饿时间内完成请求

409——对当前资源状态,请求不能完成

410——服务器上不再有此资源且无进一步的参考地址

411——服务器拒绝用户定义的Content-Length属性请求

412——一个或多个请求头字段在当前请求中错误

413——请求的资源大于服务器允许的大小

414——请求的资源URL长于服务器允许的长度

415——请求资源不支持请求项目格式

416——请求中包含Range请求头字段,在当前请求资源范围内没有range指示值,请求也不包含If-Range请求头字段

417——服务器不满足请求Expect头字段指定的期望值,如果是代理服务器,可能是下一级服务器不能满足请求

500——服务器产生内部错误

501——服务器不支持请求的函数

502——服务器暂时不可用,有时是为了防止发生系统过载

503——服务器过载或暂停维修

504——关口过载,服务器使用另一个关口或服务来响应用户,等待时间设定值较长

505——服务器不支持或拒绝支请求头中指定的HTTP版本

4.思考问题:为什么onreadystatechange的函数实现要同时判断readyState和status呢?

第一种思考方式:只使用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);
}
};
Copy after login

服务响应出错了,但还是返回了信息,这并不是我们想要的结果

如果返回不是200,而是404或者500,由于只使用readystate做判断,它不理会放回的结果是200、404还是500,只要响应成功返回了,就执行接下来的javascript代码,结果将造成各种不可预料的错误。所以只使用readyState判断是行不通的。

第二种思考方式:只使用status判断

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);
}
};
Copy after login

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

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

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

xhr.readyState === 4 && xhr.status === 200
Copy after login

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

推荐阅读:

Ajax+Struts2怎么实现用户输入验证码校验功能

Ajax怎么实现点击时不断开数据加载列表

The above is the detailed content of How to use readyState and status in Ajax. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template