jQuery中的Ajax

jQuery中的Ajax

1. 了解jQuery中的Ajax

image-20230521154952314

2. $.get()函数

2.1 语法

image-20230521155007391

2.2 $.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
<!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>
<script src="../lib/jquery-3.6.0.js"></script>
</head>

<body>
<button id="btn">$.get()发起不带参数的请求</button>
<script>

$(function () {
$("#btn").on("click", function (e) {
$.get('http://jsonplaceholder.typicode.com/posts', function (data) {
console.log(data); // 这里的 data 是服务器返回的数据
})
})
})
</script>
</body>

</html>

image-20230521155210556

2.3 $.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
<!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>
<script src="../lib/jquery-3.6.0.js"></script>
</head>

<body>
<button id="btn">$.get()发起带参数的请求</button>
<script>
$(function () {
$('#btn').on('click', function () {
// 使用 $.get() 函数发起带参数的请求时,示例代码如下
$.get('http://jsonplaceholder.typicode.com/posts', { id: 1 }, function (data) {
// 参数为{ id: 1 },只获取参数为{ id: 1 }的数据
console.log(data);
});
});
})
</script>
</body>

</html>

image-20230521155259906

3. $.post()函数

3.1 语法

image-20230521155314949

3.2 $.post()向服务器提交数据

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
<!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>
<script src="../lib/jquery-3.6.0.js"></script>
</head>

<body>
<button id="btn">$.post()向服务器提交数据</button>
<script>
$(function () {
$('#btn').on('click', function () {
$.post('http://jsonplaceholder.typicode.com/posts',// 请求的URL地址
{
userId: 0,
id: 0,
title: "Solar Rain",
body: "Solar Rain Data"
},// 提交的数据
function (data) {// 回调函数
console.log(data);
})
})
})
</script>
</body>

</html>

image-20230521155351732

4. $.ajax()函数

4.1 语法

image-20230521155412789

4.2 $.ajax()发起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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<!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>
<script src="../lib/jquery-3.6.0.js"></script>
</head>

<body>
<button id="btn">使用$.ajax()发起GET请求</button>
<script>
// $.ajax()函数的语法
// 相比于 $.get() 和 $.post() 函数,jQuery 中提供的 $.ajax() 函数,是一个功能比较综合的函数,它允许我们对Ajax 请求进行更详细的配置。
// $.ajax() 函数的基本语法如下:
// $.ajax() 方法接受一个对象作为参数,该对象包含了一些配置选项,常用的配置选项包括:

// url: 必需,表示要发送 Ajax 请求的 URL 地址。
// type: 可选,表示要发送的请求类型,如 GET、POST、PUT、DELETE 等,默认值为 GET。
// data: 可选,表示要发送的数据。
// dataType: 可选,表示服务器响应的数据类型,如 text、html、xml、json 等,默认值为智能猜测。
// success: 可选,表示 Ajax 请求成功时执行的回调函数。
// error: 可选,表示 Ajax 请求失败时执行的回调函数。

// $.ajax({
// url: 'http://example.com/api/data',
// type: 'GET',
// dataType: 'json',
// success: function (data) {
// console.log('data received:', data);
// },
// error: function (xhr, status, error) {
// console.log('error:', error);
// }
// });

$(function () {
$('#btn').on('click', function () {
// 使用 $.ajax() 发起 GET 请求时,只需要将 type 属性的值设置为 'GET' 即可:
$.ajax({
type: 'GET',// 请求的方式
url: 'http://ajax-api.itheima.net/api/books',// 请求的方式
dataType: 'json',// 这次请求数据类型
data: { id: 1 },// 这次请求要携带的数据(可选,按需求来)
success: function (data) {// 请求成功之后的回调函数
console.log(data);
}
})
})
})
</script>
</body>

</html>

image-20230521155449029

4.3 $.ajax()发起POST请求

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>
<script src="../lib/jquery-3.6.0.js"></script>
</head>

<body>
<button id="btn">使用$.ajax()发起POST请求</button>
<script>
$(function () {
$('#btn').on('click', function () {
// 使用 $.ajax() 发起 GET 请求时,只需要将 type 属性的值设置为 'POST' 即可:
$.ajax({
type: 'POST',// 请求的方式
url: 'http://jsonplaceholder.typicode.com/posts',// 请求的方式
dataType: 'json',// 这次请求数据类型
data: { // 要提交给服务器的数据
userId: 0,
id: 0,
title: "Solar Rain",
body: "Solar Rain Data"
},
success: function (data) {// 请求成功之后的回调函数
console.log(data);
}
})
})
})
</script>
</body>

</html>

image-20230521155543156

5. 接口

5.1 接口的概念

image-20230521155642038

5.2 分析接口的请求过程

5.21 通过GET方式请求接口的过程

image-20230521155651893

5.22 通过POST方式请求接口的过程

image-20230521155659758

5.3 接口测试工具

image-20230521155712445

postman、apifox等

5.4 接口文档

5.41 什么是接口文档

image-20230521155723180

5.42 接口文档的组成部分

image-20230521155731841

5.43 接口文档示例

image-20230521155739272

image-20230521155746867

image-20230521155752445

6. 案例

6.1 图书管理

image-20230521155806814

  • html
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
<!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">
</head>

<body style="padding: 15px;">
<!-- 添加图书的Panel面板 -->
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">添加文图书</h3>
</div>
<div class="panel-body form-inline">
<div class="input-group">
<div class="input-group-addon">id</div>
<input type="number" class="form-control" id="userid" placeholder="请输入">
</div>
<div class="input-group">
<div class="input-group-addon">书名</div>
<input type="text" class="form-control" id="infoid" placeholder="请输入">
</div>
<div class="input-group">
<div class="input-group-addon">作者</div>
<input type="text" class="form-control" id="title" placeholder="请输入">
</div>
<div class="input-group">
<div class="input-group-addon">出版社</div>
<input type="text" class="form-control" id="info" placeholder="请输入">
</div>

<button type="button" class="btn btn-primary" id="add">提交</button>

</div>
</div>
<!-- 图书表格 -->

<table class="table table-bordered table-hover">
<thead>
<tr>
<th>id</th>
<th>书名</th>
<th>作者</th>
<th>出版社</th>
<th>操作</th>
</tr>
</thead>
<tbody></tbody>
</table>

<script src="../lib/jquery-3.6.0.js"></script>
<script src="../lib/bootstrap.min.js"></script>
<script src="../lib/book.js"></script>
</body>

</html>
  • css(bootstrap)
  • js:拿到接口渲染数据、删除数据、添加数据
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
$(function () {
// 渲染文章数据
function getComments() {
// const infoID = []
// const title = []
// const bodyT = []

$.ajax({
url: 'http://ajax-api.itheima.net/api/books',
type: 'GET',
dataType: 'json',
// data: {id:1},
success: function (data) {
// if (data != '' || data != null) {
// data.forEach((element, i) => {
// infoID.push(data[i].id)
// title.push(data[i].title)
// bodyT.push(data[i].body)
// });
// }
// else {
// console.log('Error');
// }
// 拿到数据的字段名追加数组数据渲染总归不是最好的方法,倘若数据过多,就 不行,除非只筛选其中的某些字段

// 每次执行前先清空
$('tbody').empty();

// 去除不要的字段
for (var i = 0; i < data.data.length; i++) {
delete data.data[i].creator
delete data.data[i].createdAt
delete data.data[i].updatedAt
}

data.data.forEach((element, index) => {
const tr = document.createElement('tr')
// for (var k in data[index]):遍历 data 数组中的 index 元素中的所有属性,将它们存储在变量 k 中。
for (let k in data.data[index]) {
const td = document.createElement('td')
tr.appendChild(td)
td.innerHTML = data.data[index][k]
}
const td = document.createElement('td')
td.innerHTML = "<a href='javascript:;' data-id='" + element.id + "'>删除</a>"
tr.appendChild(td)
$('tbody').append(tr)
})
}
})
}
getComments()

// 删除文章数据
// on事件委派
$('tbody').on('click', 'a', function (e) {
const id = $(this).attr('data-id')
$.ajax({ // 3. 发起 ajax 请求,根据 id 删除对应的图书
type: 'DELETE',
url: 'http://ajax-api.itheima.net/api/books/' + id,
// data: { id: id },
success: function (data) {
console.log('DELETE success');
getComments() // 4. 删除成功后,重新加载图书列表
}
})
})

// 添加文章数据
$('#add').on('click', function () {
const id = $('#userid').val().trim()
const bookname = $('#infoid').val().trim()
const author = $('#title').val().trim()
const publisher = $('#info').val().trim()
if (id === '' || bookname === '' || author === '' || publisher === '') {
return alert('请完整填写信息!')
}
$.ajax({
type: 'POST',
data: {
id: id,
bookname: bookname,
author: author,
publisher: publisher
},// 提交的数据
url: 'http://ajax-api.itheima.net/api/books',
success: function (data) {
console.log('ADD success');
getComments()
// $('input').val('') // 5. 清空文本框内容
}
})
})
})

6.2 聊天机器人

image-20230521160206857

  • html
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
<!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" />
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/main.css" />
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/jquery.mousewheel.js"></script>
<title>聊天机器人</title>
</head>

<body>
<div class="wrap">
<!-- 头部 Header 区域 -->
<div class="header">
<h3>小思同学</h3>
<img src="img/person01.png" alt="icon" />
</div>
<!-- 中间 聊天内容区域 -->
<div class="main">
<ul class="talk_list" style="top: 0px;" id="talk_list">
<li class="left_word">
<img src="img/person01.png" /> <span>你好</span>
</li>
<li class="right_word">
<img src="img/person02.png" /> <span>你好哦</span>
</li>
</ul>
<!-- 语音 -->
<audio src="" id="voice" autoplay style="display: none;"></audio>
<div class="drag_bar" style="display: none;">
<div class="drager ui-draggable ui-draggable-handle" style="display: none; height: 412.628px;"></div>
</div>
</div>
<!-- 底部 消息编辑区域 -->
<div class="footer">
<img src="img/person02.png" alt="icon" />
<input type="text" id="say" placeholder="说点什么吧..." class="input_txt" />
<input type="button" id="send" value="发 送" class="input_sub" />
</div>
</div>
<script type="text/javascript" src="js/scroll.js"></script>
<script src="js/chat.js"></script>
</body>

</html>
  • css
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
body {
font-family: 'Microsoft YaHei';
}

.wrap {
position: fixed;
width: 450px;
left: 50%;
margin-left: -225px;
top: 20px;
bottom: 20px;
border: 1px solid #ebebeb;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 0 30px rgba(0, 0, 0, 0.1);
overflow: hidden;
}

.header {
height: 55px;
background: linear-gradient(90deg, rgba(246, 60, 47, 0.6), rgba(128, 58, 242, 0.6));
overflow: hidden;
}

.header h3 {
color: #faf3fc;
line-height: 55px;
font-weight: normal;
float: left;
letter-spacing: 2px;
margin-left: 25px;
font-size: 18px;
text-shadow: 0px 0px 5px #944846;
}

.header img {
float: right;
margin: 7px 25px 0 0;
border-radius: 20px;
box-shadow: 0 0 5px #f7f2fe;
}

.main {
position: absolute;
left: 0;
right: 0;
top: 55px;
bottom: 55px;
background-color: #f4f3f3;
box-sizing: border-box;
padding: 10px 0;
overflow: hidden;
}

.talk_list {
position: absolute;
width: 100%;
left: 0px;
top: 0px;
}

.talk_list li {
overflow: hidden;
margin: 20px 0px 30px;
}

.talk_list .left_word img {
float: left;
margin-left: 20px;
}

.talk_list .left_word span {
float: left;
background-color: #fe9697;
padding: 10px 15px;
max-width: 290px;
border-radius: 12px;
font-size: 16px;
color: #fff;
margin-left: 13px;
position: relative;
line-height: 24px;
}

.talk_list .left_word span:before {
content: '';
position: absolute;
left: -8px;
top: 3px;
width: 13px;
height: 12px;
background: url('../img/corner01.png') no-repeat;
}

.talk_list .right_word img {
float: right;
margin-right: 20px;
}

.talk_list .right_word span {
float: right;
background-color: #fff;
padding: 10px 15px;
max-width: 290px;
border-radius: 12px;
font-size: 16px;
color: #000;
margin-right: 13px;
position: relative;
line-height: 24px;
}

.talk_list .right_word span:before {
content: '';
position: absolute;
right: -8px;
top: 3px;
width: 13px;
height: 12px;
background: url('../img/corner02.png') no-repeat;
}

.drag_bar {
position: absolute;
right: 0px;
top: 0px;
background-color: #fff;
height: 100%;
width: 6px;
box-sizing: border-box;
border-bottom: 1px solid #f4f3f3;
}

.drager {
position: absolute;
left: 0px;
top: 0px;
background-color: #cdcdcd;
height: 100px;
width: 6px;
border-radius: 3px;
cursor: pointer;
}

.footer {
width: 100%;
height: 55px;
left: 0px;
bottom: 0px;
background-color: #fff;
position: absolute;
}

.footer img {
float: left;
margin: 8px 0 0 20px;
}

.input_txt {
float: left;
width: 270px;
height: 37px;
border: 0px;
background-color: #f4f3f3;
margin: 9px 0 0 20px;
border-radius: 8px;
padding: 0px;
outline: none;
text-indent: 15px;
}

.input_sub {
float: left;
width: 70px;
height: 37px;
border: 0px;
background-color: #fe9697;
margin: 9px 0 0 15px;
border-radius: 8px;
padding: 0px;
outline: none;
color: #fff;
cursor: pointer;
}

.loading {
text-align: center;
}
  • js
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
$(function () {
// 初始化右侧滚动条
// 这个方法定义在scroll.js中

// 为发送按钮绑定鼠标点击事件
$('#send').on('click', function () {
info()
})

// 回车
$('#say').on('keydown', function (e) {
// e.keyCode 可以获取到当前按键的编码
e.keyCode === 13 && info()
// 调用按钮元素的 click 函数,可以通过编程的形式触发按钮的点击事件
// $('#send').click()
})

//
function info() {
const text = $('#say').val().trim()
if (text.length <= 0) {
return $('#say').val('')
}

// 如果用户输入了聊天内容,则将聊天内容追加到页面上显示
const content = $('<li class="right_word"><img src="img/person02.png" /><span>' + text + '</span></li><li class="loading">加载中...</li>')
$('#talk_list').append(content)

// 输入完清空文本框
$('#say').val('')

// 获取聊天机器人发送回来的消息
getMsg(text)

// 重置滚动条位置
resetui()
}

// 获取聊天机器人发送回来的消息
function getMsg(parameter) {
$.ajax({
type: 'GET',
url: 'http://ajax-api.itheima.net/api/robot',
data: {
spoken: parameter
},
success: function (res) {
if (res.message === 'success') {
const msg = res.data.info.text
// TODO: 发起请求,将机器人的聊天消息转为语音格式
getVoice(msg)
// 返回回复
$('#talk_list').append('<li class="left_word"><img src="img/person01.png" /> <span>' + msg + '</span></li>')
// 删除数据加载停止提示
$('.loading').remove()
resetui()
}
}
})
}

// 将聊天机器人发送回来的消息转换为语音
function getVoice(parameter) {
$.ajax({
type: 'GET',
url: 'http://ajax-base-api-t.itheima.net/api/synthesize',
data: {
text: parameter
},
success: function (res) {
if (res.status === 200) {
$('#voice').attr('src', res.voiceUrl)
}
}
})
}
})