diff --git "a/19\345\275\255\345\213\207\346\226\214/Ajax.md" "b/19\345\275\255\345\213\207\346\226\214/Ajax.md" new file mode 100644 index 0000000000000000000000000000000000000000..dc2d7f7ab2ffb5a4e25f2c9e35552c1cc8213782 --- /dev/null +++ "b/19\345\275\255\345\213\207\346\226\214/Ajax.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 diff --git "a/19\345\275\255\345\213\207\346\226\214/\347\231\273\345\275\225\346\241\210\344\276\213.md" "b/19\345\275\255\345\213\207\346\226\214/\347\231\273\345\275\225\346\241\210\344\276\213.md" new file mode 100644 index 0000000000000000000000000000000000000000..3aae8ede1dab28db41cdbbb50fe4dce2d7ec456a --- /dev/null +++ "b/19\345\275\255\345\213\207\346\226\214/\347\231\273\345\275\225\346\241\210\344\276\213.md" @@ -0,0 +1,70 @@ +## 登录案例 + +```html + +``` + +## 问答机器人 + +```html + +``` \ No newline at end of file