search
HomeWeb Front-endJS TutorialDiscuss issues related to readyState and status in Ajax

This article mainly introduces relevant information on issues related to readyState (status value) and status (status code) in Ajax. It is very good and has reference value. Friends who need it can refer to it

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);
}
};

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

readyState refers to the experience of running AJAX Several states have been passed, and the steps that will respond regardless of whether the access is successful can be understood as AJAX running steps. Use "ajax.readyState" to obtain the

status, which means that regardless of whether the AJAX access is successful or not, by The HTTP protocol uses "ajax.status" to obtain the HTTP header information code returned by the server based on the submitted information.
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 begins to send the request

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

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

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

3. What is status

status is the XMLHttpRequest object An attribute indicating the response HTTP status code

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

1xx: Information response class, indicating that the request is received and continued 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 syntax errors or cannot be executed correctly

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

100 - The client must continue Make a request

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

200——The transaction is successful

201——Prompt to know the URL of the new file

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

203——The return information is uncertain or incomplete

204——The request was received, but the return information was empty

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

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

300 - The requested Resource available in multiple places

301 - Request data removed

302 - Request data found at other address

303 - Customers advised to visit other URLs or visit Method

304——The client has performed GET, but the file has not changed

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

306——Previous Code used in a version of HTTP, no longer used in the current version

307 - Declaring that the requested resource is temporarily deleted

400 - Error request, such as syntax error

401 - Request authorization failed

402 - Preserve 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 inaccessible

407 - Similar to 401 , the user must first obtain authorization on the proxy server

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

409——The request cannot be completed for the current resource status

410 - This resource no longer exists on the server and has no further reference address

411 - The server rejected the user-defined Content-Length attribute request

412 - One or Multiple request header fields are wrong 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 request item format

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

417 - The server does not meet the expectations specified in the Expect header field of the request. If it is a proxy server, it may be that the next-level server cannot meet the request.

500 - The server generates an internal error

501 - The server does not support the requested function

502 - The server is temporarily unavailable, sometimes to prevent system overload

503 - The server is overloaded or suspended for maintenance

504——The gateway is overloaded, the server uses another gate or service to respond to the user, and the waiting time is set to a long value

505——The server does not support or refuses to support the HTTP version specified in the request header

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);
}
};

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

如果返回不是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);
}
};

事实上,结果却不像预期那样。响应码确实是返回了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

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

全面解析$.Ajax()方法参数(图文教程)

IE8下Ajax缓存问题及解决办法

浅谈ajax请求技术

The above is the detailed content of Discuss issues related to 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
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.