From 1f4b8366b3804ddcb67e054a5e03d89be172b529 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E8=B5=96=E5=BF=83=E5=A6=8D?= <2392642810@qq.com>
Date: Wed, 6 Dec 2023 22:58:16 +0800
Subject: [PATCH] =?UTF-8?q?=E9=A2=84=E4=B9=A0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../20231206 Ajax\351\242\204\344\271\240.md" | 149 ++++++++++++++++++
1 file changed, 149 insertions(+)
create mode 100644 "03 \350\265\226\345\277\203\345\246\215/20231206 Ajax\351\242\204\344\271\240.md"
diff --git "a/03 \350\265\226\345\277\203\345\246\215/20231206 Ajax\351\242\204\344\271\240.md" "b/03 \350\265\226\345\277\203\345\246\215/20231206 Ajax\351\242\204\344\271\240.md"
new file mode 100644
index 0000000..864bf28
--- /dev/null
+++ "b/03 \350\265\226\345\277\203\345\246\215/20231206 Ajax\351\242\204\344\271\240.md"
@@ -0,0 +1,149 @@
+### Ajax
+
+```html
+//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对象
+
+```js
+const xhr = new XMLHttpRequest();
+```
+
+2.利用onreadystatechange属性,封装一个函数,用于监听 readyState的变化。
+
+```js
+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 用于表示请求成功)
+
+```js
+if (xhr.status >= 200 && xhr.status < 300 ){
+ console.log(xhr.responseText);
+}
+```
+
+所以要想请求成功完成,必须要满足上面两个条件。
+
+3.准备发送请求
+
+```js
+xhr.open('GET','text.json', true);
+```
+
+参数1:选用"GET"或者“POST”的请求方式
+
+参数2:发送请求的地址
+
+参数3:是否异步
+
+4.发送请求
+
+```js
+xhr.send(null)
+```
+
+ 注意:send() 的参数是通过请求体携带的数据,而GET请求是通过请求头携带数据的,所以要把send的参数置为null
+
+```html
+
+```
+
+### 复习
+
+```html
+
+```
+
--
Gitee