From fdd96679346f651bf77d2fce926d05a583b26741 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E6=99=BA=E7=BF=94?= <2045602860@qq.com> Date: Thu, 7 Dec 2023 03:41:50 +0000 Subject: [PATCH] =?UTF-8?q?34=20=E5=88=98=E6=99=BA=E7=BF=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 刘智翔 <2045602860@qq.com> --- .../Ajax\351\242\204\344\271\240.md" | 148 ++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 "34 \345\210\230\346\231\272\347\277\224/Ajax\351\242\204\344\271\240.md" diff --git "a/34 \345\210\230\346\231\272\347\277\224/Ajax\351\242\204\344\271\240.md" "b/34 \345\210\230\346\231\272\347\277\224/Ajax\351\242\204\344\271\240.md" new file mode 100644 index 0000000..cf78ff7 --- /dev/null +++ "b/34 \345\210\230\346\231\272\347\277\224/Ajax\351\242\204\344\271\240.md" @@ -0,0 +1,148 @@ +### 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 + +``` \ No newline at end of file -- Gitee