# Day03_AJAX原理
## 知识点自测
1. 以下哪个方法可以把 JS 数据类型转成 JSON 字符串类型?
A. JSON.stringify()
B. JSON.parse()
<details>
<summary>答案</summary>
<ul>
<li>选择A</li>
</ul>
</details>
2. 以下哪个方法,会延迟一段时间后,再执行函数体,并执行一次就停止?
A. setTimeout(函数体, 毫秒值)
B. setInterval(函数体, 毫秒值)
<details>
<summary>答案</summary>
<ul>
<li>选择A</li>
</ul>
</details>
3. 下面代码 result 结果是多少?
```js
let obj = {
status: 240
}
const result = obj.status >= 200 && obj.status < 300
```
A. true
B. 大于
C. 240
D. false
<details>
<summary>答案</summary>
<ul>
<li>选A</li>
</ul>
</details>
4. 下面代码运行结果是多少?
```js
let result = 'http://www.baidu.com'
result += '?a=10'
result += '&b=20'
```
A:'http://www.baidu.com'
B:'?a=10'
C:'&b=20'
D:'http://www.baidu.com?a=10&b=20'
<details>
<summary>答案</summary>
<ul>
<li>选D</li>
</ul>
</details>
5. 哪个事件能实时检测到输入框值的变化?
A:input 事件
B:change 事件
<details>
<summary>答案</summary>
<ul>
<li>选A</li>
</ul>
</details>
## 目录
* XMLHttpRequest 的学习
* Promise
* 封装简易版 axios
* 案例 - 天气预报
## 学习目标
1. 了解原生 AJAX 语法 - XMLHttpRequest(XHR)
2. 了解 Promise 的概念和使用
3. 了解 axios 内部工作的大概过程(XHR + Promise)
4. 案例 - 天气预报
## 01.XMLHttpRequest - 基础使用
### 目标
了解 AJAX 原理 XHR 的基础使用
### 讲解
1. AJAX 是浏览器与服务器通信的技术,采用 XMLHttpRequest 对象相关代码
2. axios 是对 XHR 相关代码进行了封装,让我们只关心传递的接口参数
3. 学习 XHR 也是了解 axios 内部与服务器交互过程的真正原理
![image-20230221182835545](https://p.ipic.vip/zfmu41.jpg)
4. 语法如下:
```js
const xhr = new XMLHttpRequest()
xhr.open('请求方法', '请求url网址')
xhr.addEventListener('loadend', () => {
// 响应结果
console.log(xhr.response)
})
xhr.send()
```
![image-20230221183057392](https://p.ipic.vip/2bablm.jpg)
5. 需求:以一个需求来体验下原生 XHR 语法,获取所有省份列表并展示到页面上
6. 代码如下:
```javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>XMLHttpRequest_基础使用</title>
</head>
<body>
<p class="my-p"></p>
<script>
/**
* 目标:使用XMLHttpRequest对象与服务器通信
* 1. 创建 XMLHttpRequest 对象
* 2. 配置请求方法和请求 url 地址
* 3. 监听 loadend 事件,接收响应结果
* 4. 发起请求
*/
// 1. 创建 XMLHttpRequest 对象
const xhr = new XMLHttpRequest()
// 2. 配置请求方法和请求 url 地址
xhr.open('GET', 'http://hmajax.itheima.net/api/province')
// 3. 监听 loadend 事件,接收响应结果
xhr.addEventListener('loadend', () => {
console.log(xhr.response)
const data = JSON.parse(xhr.response)
console.log(data.list.join('<br>'))
document.querySelector('.my-p').innerHTML = data.list.join('<br>')
})
// 4. 发起请求
xhr.send()
</script>
</body>
</html>