ajax方法XHR.readyState五种状态与示例
XHR.readyState == 状态(0,1,2,3,4),而且状态也是不可逆的:
0:请求未初始化,还没有调用 open()。
1:请求已经建立,但是还没有发送,还没有调用 send()。
2:请求已发送,正在处理中(通常现在可以从响应中获取内容头)。
3:请求在处理中;通常响应中已有部分数据可用了,没有全部完成。
4:响应已完成;您可以获取并使用服务器的响应了。
下面是一个demo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | <!DOCTYPE html> <html lang= "en" > <head> <meta charset= "UTF-8" > <meta name= "viewport" content= "width=device-width, initial-scale=1.0" > <meta http-equiv= "X-UA-Compatible" content= "ie=edge" > <title>Document</title> <style> *{ margin: 0; padding: 0; } #url{ width: 1000px; height: 30px; outline: none; border: 1px solid #000; border-radius: 5px; margin-left: 10px; } #btn{ width: 90px; height: 30px; outline: none; border: 1px solid #000; border-radius: 5px; cursor: pointer; } </style> </head> <body> <div> <label for = "url" > URL:<input type= "text" placeholder= "请输入要检测的URL" id= "url" > </label> </div> <br> <button class = "btn" id= "btn" >点击测试</button> <div id= "content" > </div> </body> <script> var str = '' document.getElementById( 'btn' ).onclick = function(){ var xhr = new XMLHttpRequest(); var url = document.getElementById( 'url' ).value; if (!url) { alert( '请输入URL' ); return false ; } // console.log(url) console.log(xhr.status, xhr.readyState) // 0,0 xhr.onreadystatechange=function(){ // console.log(xhr) if (xhr.status === 200){ console.log(xhr.status, xhr.readyState) //200,2;200,3;200,4 str += `status:${xhr.status}` if (xhr.readyState === 4){ // console.log(xhr.getAllResponseHeaders()) str += xhr.getAllResponseHeaders() + '<br/>' } } document.getElementById( 'content' ).innerHTML = str; } xhr.open( "GET" ,url, true ); console.log(xhr.status, xhr.readyState) // 0,1 xhr.send( null ) } </script> </html> |
如果觉得文章不错,可以给小编发个红包给予鼓励.
你要觉得这篇文章比较好,记得点推荐!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」