From 6f832e690b81a2800eb66166cba2035b835f2772 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?22=20=E8=82=96=E9=92=9F=E5=87=AF=E9=9F=A9?= <3175644391@qq.com> Date: Thu, 7 Dec 2023 13:11:38 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../20231207 Ajax.md" | 147 ++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 "22 \350\202\226\351\222\237\345\207\257\351\237\251/20231207 Ajax.md" diff --git "a/22 \350\202\226\351\222\237\345\207\257\351\237\251/20231207 Ajax.md" "b/22 \350\202\226\351\222\237\345\207\257\351\237\251/20231207 Ajax.md" new file mode 100644 index 0000000..057101f --- /dev/null +++ "b/22 \350\202\226\351\222\237\345\207\257\351\237\251/20231207 Ajax.md" @@ -0,0 +1,147 @@ +### Ajax + +``` +//test.josn的代码 +{ + "reply":"我收到啦!" +} + +const xhr = new XMLHttpRequest(); +xhr.onreadystatechange = () => { + if (xhr.readyState !== 4) return; + if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) { + console.log(xhr.responseText); + } +}; +xhr.open('GET', 'text.json', true); +xhr.send(null); + +// “replay” : {"我收到啦!",“”} +``` + +1.创建xhr对象 + +``` +const xhr = new XMLHttpRequest(); +``` + +2.利用onreadystatechange属性,封装一个函数,用于监听 readyState的变化。 + +``` +xhr.onreadystatechange = () => { +if (xhr.readyState !== 4) return; +if (xhr.status >= 200 && xhr.status < 300 ){ + console.log(xhr.responseText); + } +}; +``` + +2.1在xhr对象执行收发数据的时候,它会经历五种状态: + +| Ajax状态码 | 状态 | +| ---------- | ------------------------------------------------------------ | +| 0 | (**未初始化**)未启动 | +| 1 | (**启动**)已经调用 open(),但尚未调用 send() | +| 2 | (**发送**)发送状态,已经调用 send(),但尚未接收到响应 | +| 3 | (**接收**)已经接收到部分响应数据 | +| 4 | (**完成**)已经接收到全部响应数据,而且已经可以在浏览器中使用了 | + +2.2判断HTTP状态码是否为200-299 + +Ajax状态码为4是不够的,这仅仅表明收到服务器端响应的全部数据,并不能保障数据都是正确的。 + +所以,我们还需要判断HTTP的状态码,判断xhr对象的status属性值是否在200到300之间(200-299 用于表示请求成功) + +``` +if (xhr.status >= 200 && xhr.status < 300 ){ + console.log(xhr.responseText); +} +``` + +所以要想请求成功完成,必须要满足上面两个条件。 + +3.准备发送请求 + +``` +xhr.open('GET','text.json', true); +``` + +参数1:选用"GET"或者“POST”的请求方式 + +参数2:发送请求的地址 + +参数3:是否异步 + +4.发送请求 + +``` +xhr.send(null) +``` + +注意:send() 的参数是通过请求体携带的数据,而GET请求是通过请求头携带数据的,所以要把send的参数置为null + +``` + +``` + +### 复习 + +```html + +``` \ No newline at end of file -- Gitee