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); } };
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 meaning0: Initialization, the XMLHttpRequest object has not yet completed initialization 1: Loading, the XMLHttpRequest object starts to send the request2: Loading is completed, the request of the XMLHttpRequest object is sent3: Parsing, the XMLHttpRequest object starts to read the server's response4: Completed, the XMLHttpRequest object reads the server response and ends3. 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 categories1xx: Information response type, indicating receipt Request and continue processing2xx: Processing success response class, indicating that the action was successfully received, understood and accepted3xx: Redirect response class, in order to complete the specified action, further processing must be accepted4xx: Client error, the client request contains asyntax error or cannot be executed correctly
5xx: Server error, the server cannot correctly execute a correct request100——The client must continue to make the request101——The client requires the server to convert the HTTP protocol version according to the request200——The transaction is successful201——Prompt Know the URL of the new file202——Accepted and processed, but the processing was not completed203——Return information is uncertain or incomplete204——Request received , but the return information is empty205——The server has completed the request, the user agent must reset the currently browsed files206——The server has completed some users’ GET requests300 - 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 methods304——The client has executed GET, but the file has not changed305——The requested resource must be obtained from the address specified by the server306 - 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 error401——Request authorization failed402——Retain valid ChargeTo header response403——Request not allowed404—— — 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); } };
服务响应出错了,但还是返回了信息,这并不是我们想要的结果
如果返回不是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
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
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!

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 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.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software