Ajax加强

Ajax加强

1. XMLHttpRequest的基本使用

1.1 什么XMLHttpRequest

image-20230521162925954

1.2 使用xhr发起GET请求

image-20230521162936266

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
26
27
28
29
30
31
32
33
34
<!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>使用xhr发起GET请求</title>
</head>

<body>
<script>
// 步骤:
// 1. 创建 xhr 对象
const xhr = new XMLHttpRequest();
// 2. 调用 open 函数,指定 请求方式 与 URL地址
xhr.open('GET', 'http://ajax-api.itheima.net/api/books')
// 3. 调用 xhr.send() 函数
xhr.send()
// 4. 监听 onreadystatechange 事件
xhr.onreadystatechange = function () {
// 4.1 监听 xhr 对象的请求状态 readyState ;与服务器响应的状态 status
// xhr.readyState === 4 && xhr.status === 200固定写法
if (xhr.readyState === 4 && xhr.status === 200) {
// 4.2 打印服务器响应回来的数据
document.write(typeof xhr.responseText)
document.write(xhr.responseText)
console.log(xhr.responseText)
}
}
</script>
</body>

</html>

1.3 了解xhr对象的readyState属性

image-20230521163046506

1.4 使用xhr发起带参数的GET请求

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
26
27
28
29
30
31
32
33
34
35
36
37
<!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>Document</title>
</head>

<body>
<script>
// 使用 xhr 对象发起带参数的 GET 请求时,只需在调用 xhr.open 期间,为 URL 地址指定参数即可:// ...省略不必要的代码
// xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1')
// // ...省略不必要的代码
// 这种在 URL 地址后面拼接的参数,叫做查询字符串。
// 要根据接口文档查看

// 1. 创建 XHR 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数,指定 请求方式 与 URL地址
xhr.open('GET', 'http://ajax-api.itheima.net/api/books/87070')
// 3. 调用 send 函数,发起 Ajax 请求
xhr.send()
// 4. 监听 onreadystatechange 事件
xhr.onreadystatechange = function () {
// 4.1 监听 xhr 对象的请求状态 readyState ;与服务器响应的状态 status
if (xhr.readyState === 4 && xhr.status === 200) {
// 4.2 打印服务器响应回来的数据
document.write(xhr.responseText)
console.log(xhr.responseText)
}
}
</script>
</body>

</html>

1.5 查询字符串

1.51 什么是查询字符串

image-20230521163128642

1.52 GET请求携带参数的本质

image-20230521163136505

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
26
27
28
29
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="/lib/jquery-3.6.0.js"></script>
</head>

<body>
<script>
$.ajax({
method: 'GET',
url: 'http://ajax-api.itheima.net/api/books/87070',
// data: {
// id: 87070,
// bookname: '铠甲勇士'
// },
success: function (res) {
document.write(res)
console.log(res)
}
})
</script>
</body>

</html>

1.6 URL编码与解码

1.61 什么是URL编码

image-20230521163242505

1.62 如何对URL进行编码与解码

image-20230521163250965

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
26
27
28
29
30
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>

<body>
<script>
// 如何对URL进行编码与解码
// 浏览器提供了 URL 编码与解码的 API,分别是:

// encodeURI() 编码的函数
var str = '太阳雨'
var str2 = encodeURI(str)
document.write(str2)
console.log(str2)

// decodeURI() 解码的函数
console.log('----------')
var str3 = decodeURI('%E5%A4%AA%E9%98%B3%E9%9B%A8')
document.write(str3)
console.log(str3)
</script>
</body>

</html>

1.63 URL编码的注意事项

image-20230521163331131

1.7 使用xhr发起POST请求

image-20230521163422060

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
26
27
28
29
30
31
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>

<body>
<script>
// 1. 创建 xhr 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数
xhr.open('POST', 'http://ajax-api.itheima.net/api/books')
// 3. 设置 Content-Type 属性
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// 4. 调用 send 函数
xhr.send('bookname=水浒传&author=施耐庵&publisher=上海图书出版社')
// 5. 监听事件
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 201) {
document.write(xhr.responseText)
console.log(typeof xhr.responseText)
}
}
</script>
</body>

</html>

2. 数据交换格式

2.1 什么是数据交换格式

image-20230521163545840

2.2 XML

2.21 什么是XML

image-20230521163559125

2.22 XML和HTML的区别

image-20230521163606134

2.23 XML的缺点

image-20230521163612845

2.3 JSON

2.31 什么是JSON

image-20230521163624745

2.32 JSON的两种结构

image-20230521163634292

2.33 对象结构

image-20230521163644572

2.34 数组结构

image-20230521163658769

2.35 JSON语法注意事项

image-20230521163709166

2.36 JSON和JS对象的关系

image-20230521163717950

2.37 JSON和JS对象的互转

image-20230521163724988

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
26
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>

<body>
<script>
// 要实现从 JSON 字符串转换为 JS 对象,使用 JSON.parse() 方法:
// var jsonStr = '{"a": "Hello", "b": "world"}'
// var obj = JSON.parse(jsonStr)
// console.log(obj)

// 要实现从 JS 对象转换为 JSON 字符串,使用 JSON.stringify() 方法:
var obj2 = { a: 'hello', b: 'world', c: false }
var str = JSON.stringify(obj2)
console.log(str)
console.log(typeof str)//string
</script>
</body>

</html>

2.38 序列化和反序列化

image-20230521163812599

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
26
27
28
29
30
31
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>

<body>
<script>
var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://ajax-api.itheima.net/api/books')
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.write(xhr.responseText)
console.log(xhr.responseText)
console.log(typeof xhr.responseText)//string

// 字符串转对象
var result = JSON.parse(xhr.responseText)
document.write(result)
console.log(result)
}
}
</script>
</body>

</html>

3. 封装自己的Ajax函数

3.1 要实现的效果

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!-- 1. 导入自定义的ajax函数库 -->
<script src="/lib/solar.js"></script>
</head>

<body>
<script>

// 2. 调用自定义的 itheima 函数,发起 Ajax 数据请求
solar({
type: 'GET', //'请求类型'
url: 'http://ajax-api.itheima.net/api/books', //'请求地址'
success: function (res) { // 成功的回调函数
document.write(res) // 打印数据
console.log(res)
}
})

solar({
type: 'POST', //'请求类型'
url: 'http://ajax-api.itheima.net/api/books', //'请求地址'
data: { // 请求参数对象
bookname: '水浒传',
author: '施耐庵',
publisher: '北京图书出版社'
},
success: function (res) { // 成功的回调函数
document.write(JSON.stringify(res)) // 打印数据
console.log(res)
}
})
</script>
</body>

</html>

3.2 定义options参数选项

image-20230521163908965

3.3 处理data参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 1.处理data参数
// 需要把 data 对象,转化成查询字符串的格式,从而提交给服务器,因此提前定义 resolveData 函数如下
/**
* 处理 data 参数
* @param {data} 需要发送到服务器的数据
* @returns {string} 返回拼接好的查询字符串 name=zs&age=10
*/
function resolveData(data) {
const arr = []
for (const k in data) {
arr.push(k + '=' + data[k])
}
return arr.join('&')
}

3.4 定义函数

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
26
27
28
// 2.定义solar函数
// 在 solar() 函数中,需要创建 xhr 对象,并监听 onreadystatechange 事件
function solar(options) {
const xhr = new XMLHttpRequest()
// 拼接查询字符串
const qs = resolveData(options.data)

// 3.判断请求的类型
// 不同的请求类型,对应 xhr 对象的不同操作,因此需要对请求类型进行 if … else … 的判断:
if (options.type.toUpperCase() === 'GET') {
// 发起 GET 请求
xhr.open(options.type, options.url + '?' + qs)
xhr.send()
} else if (options.type.toUpperCase() === 'POST') {
// 发起 POST 请求
xhr.open(options.type, options.url)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send(qs)
}

// 监听请求状态改变的事件
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 201)) {
const result = JSON.parse(xhr.responseText)
options.success(result)
}
}
}

3.5 判断请求的类型

1
2
3
4
5
6
7
8
9
10
11
12
// 3.判断请求的类型
// 不同的请求类型,对应 xhr 对象的不同操作,因此需要对请求类型进行 if … else … 的判断:
if (options.type.toUpperCase() === 'GET') {
// 发起 GET 请求
xhr.open(options.type, options.url + '?' + qs)
xhr.send()
} else if (options.type.toUpperCase() === 'POST') {
// 发起 POST 请求
xhr.open(options.type, options.url)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send(qs)
}

3.6 完整代码

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 1.处理data参数
// 需要把 data 对象,转化成查询字符串的格式,从而提交给服务器,因此提前定义 resolveData 函数如下
/**
* 处理 data 参数
* @param {data} 需要发送到服务器的数据
* @returns {string} 返回拼接好的查询字符串 name=zs&age=10
*/
function resolveData(data) {
const arr = []
for (const k in data) {
arr.push(k + '=' + data[k])
}
return arr.join('&')
}

// 2.定义solar函数
// 在 solar() 函数中,需要创建 xhr 对象,并监听 onreadystatechange 事件
function solar(options) {
const xhr = new XMLHttpRequest()
// 拼接查询字符串
const qs = resolveData(options.data)

// 3.判断请求的类型
// 不同的请求类型,对应 xhr 对象的不同操作,因此需要对请求类型进行 if … else … 的判断:
if (options.type.toUpperCase() === 'GET') {
// 发起 GET 请求
xhr.open(options.type, options.url + '?' + qs)
xhr.send()
} else if (options.type.toUpperCase() === 'POST') {
// 发起 POST 请求
xhr.open(options.type, options.url)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send(qs)
}

// 监听请求状态改变的事件
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 201)) {
const result = JSON.parse(xhr.responseText)
options.success(result)
}
}
}

4. XMLHttpRequest Level2的新特性

4.1 旧版XMLHttpRequest的缺点

image-20230521164159520

4.2 XMLHttpRequest Level2的新功能

image-20230521164206941

4.3 设置HTTP请求时限

image-20230521164216411

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>

<body>
<script>
// 认识XMLHttpRequest Level2
// 1. 旧版XMLHttpRequest的缺点
// ① 只支持文本数据的传输,无法用来读取和上传文件
// ② 传送和接收数据时,没有进度信息,只能提示有没有完成

// 2. XMLHttpRequest Level2的新功能
// ① 可以设置 HTTP 请求的时限
// ② 可以使用 FormData 对象管理表单数据
// ③ 可以上传文件
// ④ 可以获得数据传输的进度信息
var xhr = new XMLHttpRequest()

// 设置 超时时间
// 有时,Ajax 操作很耗时,而且无法预知要花多少时间。
// 如果网速很慢,用户可能要等很久。
// 新版本的XMLHttpRequest 对象,增加了 timeout 属性,可以设置 HTTP 请求的时限:
xhr.timeout = 30
// 设置超时以后的处理函数
// 上面的语句,将最长等待时间设为 3000 毫秒。过了这个时限,就自动停止HTTP请求。
// 与之配套的还有一个timeout 事件,用来指定回调函数:
xhr.ontimeout = function () {
console.log('请求超时了!')
}

xhr.open('GET', 'http://ajax-api.itheima.net/api/books')
xhr.send()

xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
</script>
</body>

</html>

4.4 FormData对象管理表单数据

4.41 基本使用

image-20230521164343202

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
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>

<body>
<script>
// Ajax 操作往往用来提交表单数据。
// 为了方便表单处理,HTML5 新增了一个 FormData 对象,可以模拟表单操作:

// 1. 创建 FormData 实例
var fd = new FormData()
// 2. 调用 append 函数,向 fd 中追加数据
fd.append('author', 'zs')
fd.append('bookname', '123456')

// 3. 创建 XHR 对象
var xhr = new XMLHttpRequest()
// 4. 指定请求类型与URL地址
xhr.open('POST', 'http://ajax-api.itheima.net/api/data')
xhr.send(fd)
// 5. 直接提交 FormData 对象,这与提交网页表单的效果,完全一样
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText))
}
}
</script>
</body>

</html>

4.42 获取表单值

image-20230521164424329

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>

<body>

<form id="form1">
<input type="text" name="uname" autocomplete="off" />
<input type="password" name="upwd" />
<button type="submit">提交</button>
</form>

<script>
// 1. 通过 DOM 操作,获取到 form 表单元素
var form = document.querySelector('#form1')
// 监听表单元素的 submit 事件
form.addEventListener('submit', function (e) {
// 阻止表单的默认提交行为
e.preventDefault()
// 根据 form 表单创建 FormData 对象,会自动将表单数据填充到 FormData 对象中
// 创建 FormData,快速获取到 form 表单中的数据
var fd = new FormData(form)

var xhr = new XMLHttpRequest()
xhr.open('POST', 'http://ajax-api.itheima.net/api/data')
xhr.send(fd)

xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText))
}
}
})
</script>

</body>

</html>

4.5 上传文件

4.51 实现步骤

image-20230521164524704

4.52 定义UI结构

image-20230521164531709

4.53 验证是否选择了文件

image-20230521164538351

4.54 向FormData中追加文件

image-20230521164544622

4.55 使用 xhr 发起上传文件的请求

image-20230521164551742

4.56 监听onreadystatechange事件

image-20230521164558829

4.57 显示文件上传进度

  1. 监听事件

image-20230521164616115

  1. 导入需要的库

image-20230521164625659

  1. 基于Bootstrap渲染进度条

image-20230521164632867

  1. 监听上传进度的事件

image-20230521164656387

  1. 监听上传完成的事件

  1. 上传文件完整代码
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!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>Document</title>
</head>

<body>
<!-- 1. 文件选择框 -->
<input type="file" id="file">
<!-- 2. 上传按钮 -->
<button type="submit" id="btn">上传</button>
<br />
<!-- 3. 显示上传到服务器上的图片 -->
<img src="" alt="" srcset="" id="img" width="800">

<script>
// 验证是否选择了文件
// 1. 获取上传文件的按钮
var btnUpload = document.querySelector('#btn')
// 2. 为按钮添加 click 事件监听
btnUpload.addEventListener('click', function () {
// 3. 获取到选择的文件列表
// 在Web开发中,File API提供了一组用于处理文件的JavaScript接口,其中包括一个files属性,用于获取用户在表单中选择的文件列表。
const files = document.querySelector('#file').files
if (files.length <= 0) {
return alert('请选择要上传的文件!')
}

// ...后续业务逻辑
// 向FormData中追加文件
// 1. 创建 FormData 对象
var fd = new FormData()
// 2. 向 FormData 中追加文件
fd.append('avatar', files[0])

// 使用 xhr 发起上传文件的请求
// 1. 创建 xhr 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数,指定请求类型与URL地址。其中,请求类型必须为 POST
xhr.open('POST', 'http://ajax-api.itheima.net/api/file')
// 3. 发起请求
xhr.send(fd)
// 4.监听onreadystatechange事件
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status == 200) {
var result= JSON.parse(xhr.responseText)
console.log(result.message);
if (result.message === '上传成功') {// 上传文件成功
console.log(result.data.url);
// 将服务器返回的图片地址,设置为 <img> 标签的 src 属性
document.querySelector('#img').src = result.data.url
} else {// 上传文件失败
console.log('上传失败');
}
}
}
})
</script>
</body>

</html>
  1. 上传文件加进度代码
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<!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>Document</title>
<link rel="stylesheet" href="/lib/bootstrap.min.css">
<script src="/lib/jquery-3.6.0.js"></script>
</head>

<body>
<!-- 1. 文件选择框 -->
<input type="file" id="file">
<!-- 2. 上传按钮 -->
<button type="submit" id="btn">上传</button>

<div class="progress" style="width: 500px;margin: 15px 10px;" >
<div class="progress-bar progress-bar-striped active" style="width: 0%" id="percent">
0
</div>
</div>
<br />
<!-- 3. 显示上传到服务器上的图片 -->
<img src="" alt="" srcset="" id="img" width="800">

<script>
// 验证是否选择了文件
// 1. 获取上传文件的按钮
var btnUpload = document.querySelector('#btn')
// 2. 为按钮添加 click 事件监听
btnUpload.addEventListener('click', function () {
// 3. 获取到选择的文件列表
// 在Web开发中,File API提供了一组用于处理文件的JavaScript接口,其中包括一个files属性,用于获取用户在表单中选择的文件列表。
const files = document.querySelector('#file').files
if (files.length <= 0) {
return alert('请选择要上传的文件!')
}

// ...后续业务逻辑
// 向FormData中追加文件
// 1. 创建 FormData 对象
var fd = new FormData()
// 2. 向 FormData 中追加文件
fd.append('avatar', files[0])

// 使用 xhr 发起上传文件的请求
// 1. 创建 xhr 对象
var xhr = new XMLHttpRequest()

//计算上传进度
// 新版本的 XMLHttpRequest 对象中,可以通过监听 xhr.upload.onprogress 事件,来获取到文件的上传进度
xhr.upload.onprogress = function (e) {
// e.lengthComputable 是一个布尔值,表示当前上传的资源是否具有可计算的长度
if (e.lengthComputable) {
// e.loaded 已传输的字节
// e.total 需传输的总字节
var percents = Math.ceil((e.loaded / e.total) * 100)
document.querySelector('#percent').style.width = percents + '%';
document.querySelector('#percent').innerHTML = percents + '%';
}
}
// 监听上传完成的事件
xhr.upload.onload = function () {
$('#percent')
// 移除上传中的类样式
.removeClass()
// 添加上传完成的类样式
.addClass('progress-bar progress-bar-success')
}


// 2. 调用 open 函数,指定请求类型与URL地址。其中,请求类型必须为 POST
xhr.open('POST', 'http://ajax-api.itheima.net/api/file')
// 3. 发起请求
xhr.send(fd)
// 4.监听onreadystatechange事件
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status == 200) {
var result = JSON.parse(xhr.responseText)
console.log(result.message);
if (result.message === '上传成功') {// 上传文件成功
console.log(result.data.url);
// 将服务器返回的图片地址,设置为 <img> 标签的 src 属性
document.querySelector('#img').src = result.data.url
} else {// 上传文件失败
console.log('上传失败');
}
}
}
})
</script>
</body>

</html>

5. jQuery高级用法

5.1 jQuery实现文件上传

5.11 定义UI结构

image-20230521164949025

5.12 验证是否选择了文件

image-20230521165000615

5.13 向FormData中追加文件

image-20230521165012870

5.14 使用jQuery发起上传文件的请求

image-20230521165020024

5.2 jQuery实现loading效果

5.21 ajaxStart(callback)

image-20230521165029228

5.22 ajaxStop(callback)

image-20230521165034766

5.3 完整代码

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="/lib/jquery-3.6.0.js"></script>
</head>

<body>

<!-- ui -->
<input type="file" id="file1" />
<button id="btnUpload">上传文件</button>

<br />
<img src="/lib/loading.gif" alt="" style="display: none;" id="loading" />
<img src="" alt="" srcset="" id="avatar">

<script>
$(function () {
// 监听到Ajax请求被发起了
$(document).ajaxStart(function () {
$('#loading').show()
})

// 监听到 Ajax 完成的事件
$(document).ajaxStop(function () {
$('#loading').hide()
})

$('#btnUpload').on('click', function () {
// 验证是否选择了文件
var files = $('#file1')[0].files
if (files.length <= 0) {
return alert('请选择文件后再上传!')
}

// 向FormData中追加文件
var fd = new FormData()
fd.append('avatar', files[0])

// 发起 jQuery 的 Ajax 请求,上传文件
$.ajax({
type: 'POST',
url: 'http://ajax-api.itheima.net/api/file',
data: fd,
// 不对 FormData 中的数据进行 url 编码,而是将 FormData 数据原样发送到服务器
processData: false,
// 不修改 Content-Type 属性,使用 FormData 默认的 Content-Type 值
contentType: false,
success: function (res) {
console.log(res)
$('#avatar').attr('src', res.data.url);
}
})
})
})
</script>

</body>

</html>

6. axios

6.1 什么是axios

image-20230521165109152

6.2 axios发起GET请求

image-20230521165117739

6.3 axios发起POST请求

image-20230521165125863

6.4 直接使用axios发起请求

6.41 类似jQuery的axios

image-20230521165134113

6.42 直接使用axios发起GET请求

image-20230521165140382

6.43 直接使用axios发起POST请求

image-20230521165146998

6.5 代码阐述

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!-- 导入axios库 -->
<script src="/lib/axios.js"></script>
</head>

<body>
<button id="btn1">发起GET请求</button>
<button id="btn2">发起POST请求</button>
<button id="btn3">直接使用axios发起GET请求</button>
<button id="btn4">直接使用axios发起POST请求</button>

<script>
// get
document.querySelector('#btn1').addEventListener('click', function () {
var url = 'http://ajax-api.itheima.net/api/books'
// var paramsObj = { name: 'zs', age: 20 }
// axios.get(url, { params: paramsObj }).then(function (res) {
// console.log(res)
// })
axios.get(url).then(function (res) {
console.log(res)
})
})

// post
document.querySelector('#btn2').addEventListener('click', function () {
var url = 'http://ajax-api.itheima.net/api/books'
var dataObj = { bookname: '北京', author: '顺义区', publisher: '出版社' }
axios.post(url, dataObj).then(function (res) {
console.log(res)
})
})

// axios 也提供了类似于 jQuery 中 $.ajax() 的函数,语法如下:
document.querySelector('#btn3').addEventListener('click', function () {
var url = 'http://ajax-api.itheima.net/api/books/88314'
// var paramsData = { name: '钢铁侠', age: 35 }
axios({
method: 'GET',
url: url,
// params: paramsData
}).then(function (res) {
console.log(res)
})
})

document.querySelector('#btn4').addEventListener('click', function () {
axios({
method: 'POST',
url: 'http://ajax-api.itheima.net/api/books',
data: {
bookname: '北京123',
author: '顺义区123',
publisher: '出版社123'
}
}).then(function (res) {
console.log(res)
})
})

// Axios 是专注于网络数据请求的库。
// 相比于原生的 XMLHttpRequest 对象,axios 简单易用。
// 相比于 jQuery,axios 更加轻量化,只专注于网络数据请求。
</script>
</body>

</html>