XMLHttpRequest

定义:XMLHttpRequest(XHR)对象用于与服务器交互。通过XMLHttpRequest可以在不刷新页面的情况下请求特定URL,获取数据。这允许网页在不影响用户操作的情况下,更新页面的局部内容。XMLHttpRequest在AJAX编程中被大量使用

关系:axios内部采用XMLHttpRequest与服务器交互

image-20230221182835545.png

基本使用

  1. 创建 XMLHttpRequest 对象
  2. 配置请求方法和请求 url 地址
  3. 监听 loadend 事件,接收响应结果
  4. 发起请求

image-20230221183057392.png

1
2
3
4
5
6
7
8
const xhr = new XMLHttpRequest()
xhr.open('GET', 'http://hmajax.itheima.net/api/province')
xhr.addEventListener('loadend', () => {
console.log(xhr.response)
const data = JSON.parse(xhr.response)
document.querySelector('.city').innerHTML = data.list.join(' ')
})
xhr.send()

查询参数

定义:浏览器提供给服务器的额外信息,让服务器返回浏览器想要的数据

语法http://xxxx.com/xxx/xxx?参数名1=值1&参数名2=值2

1
2
3
4
5
6
7
8
const xhr = new XMLHttpRequest()
xhr.open('GET', 'http://hmajax.itheima.net/api/city?pname=广东省')
xhr.addEventListener('loadend', () => {
console.log(xhr.response)
const data = JSON.parse(xhr.response)
document.querySelector('.city').innerHTML = data.list.join(' ')
})
xhr.send()

数据提交

需求:通过 XHR 提交用户名和密码,完成注册功能

核心
请求头设置 Content-Typeapplication/json
请求体携带 JSON 字符串

1
2
3
4
5
6
7
8
9
10
11
12
const xhr = new XMLHttpRequest()
xhr.open('POST', 'http://hmajax.itheima.net/api/register')
xhr.addEventListener('loadend', () => {
console.log(xhr.response)
})
xhr.setRequestHeader('Content-Type', 'application/json')
const user = {
username: 'Alien12345',
password: '123456789'
}
const userStr = JSON.stringify(user)
xhr.send(userStr)

image.png

Promise

定义Promise 对象用于表示一个异步操作的最终完成(或失败)及其结构值

1
2
3
4
5
6
7
8
9
10
11
12
// 1. 创建 Promise 对象
const p = new Promise((resolve, reject) => {
// 2. 执行异步任务-并传递结果
// 成功调用: resolve(值) 触发 then() 执行
// 失败调用: reject(值) 触发 catch() 执行
})
// 3. 接收结果
p.then(result => {
// 成功
}).catch(error => {
// 失败
})

好处

  1. 逻辑更清晰
  2. 了解axios函数内部运作机制
  3. 能解决回调函数地狱问题

Promise-三种状态

作用:了解Promise对象如何关联的处理函数,以及代码执行顺序

概念:一个Promise对象,必然处于以下几种状态之一

  • 待定(pending) :初始状态,既没有被兑现,也没有被拒绝
  • 已兑现(fulfilled) :意味着,操作成功完成
  • 已拒绝(rejected) :意味着,操作失败

image-20230222120815484.png

  • Promise对象一旦被兑现/拒绝,就是被敲定,状态无法再被改变

封装简易axios

了解封装axios的原理,可以更好地理解XMLHttpRequest原理和axios的用法

步骤

  1. 定义 myAxios 函数,接收配置对象,返回 Promise 对象
  2. 发起 XHR 请求,默认请求方法为 GET
  3. 调用成功/失败的处理程序
  4. 使用 myAxios 函数,发起网络请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 1. 定义简易axios函数,接收配置对象,返回promise对象
function myAxios(config) {
return new Promise((resolve, reject) => {
// 2. 发起XHR请求
const xhr = new XMLHttpRequest()
xhr.open(config.method || 'GET', config.url) // 获取请求方法,默认GET
xhr.addEventListener('loadend', () => {
// 3. 调用成功/失败的处理程序
if (xhr.status >= 200 && xhr.status < 300) {
resolve(JSON.parse(xhr.response))
} else {
reject(new Error(xhr.response))
}
})
xhr.send()
})
}
// 执行简易axios
myAxios({
url: '目标资源地址'
}).then(result => {

}).catch(error => {

})