28 Fetch API 使用指南

28 Fetch API 使用指南

Fetch API 是一种现代的网络请求方式,旨在取代传统的 XMLHttpRequest。使用 Fetch API 可以方便地发送异步 HTTP 请求,并处理响应。

基础语法

使用 Fetch API 的基本语法如下:

1
2
3
4
5
6
7
fetch(url, options)
.then(response => {
// 处理响应
})
.catch(error => {
// 处理错误
});
  • url: 请求的 URL。
  • options: 可选的配置对象,如请求方法、请求头、请求体等。

发送 GET 请求

下面是一个获取数据的示例。假设我们要请求一个 API 获取用户信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
if (!response.ok) {
throw new Error('网络错误: ' + response.status);
}
return response.json(); // 解析 JSON 数据
})
.then(data => {
console.log(data); // 处理获取的数据
})
.catch(error => {
console.error('请求失败:', error);
});

代码解释

  1. fetch() 方法发送 GET 请求。
  2. 使用 response.ok 判断响应是否成功。
  3. response.json() 方法解析响应体中的 JSON 数据。
  4. 通过 then() 方法处理成功的响应,通过 catch() 方法处理错误。

发送 POST 请求

发送 POST 请求可以使用 options 对象,设置请求方法和请求体:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const userData = {
name: 'John Doe',
email: 'john.doe@example.com'
};

fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json' // 设置请求头
},
body: JSON.stringify(userData) // 转换为 JSON 字符串
})
.then(response => {
if (!response.ok) {
throw new Error('网络错误: ' + response.status);
}
return response.json(); // 解析 JSON 数据
})
.then(data => {
console.log('创建的用户:', data); // 处理返回的用户数据
})
.catch(error => {
console.error('请求失败:', error);
});

代码解释

  1. method: 'POST' 指定请求方式为 POST。
  2. headers 中设置请求头,告诉服务器请求体的类型是 JSON。
  3. body 中使用 JSON.stringify() 方法将JavaScript 对象转换为 JSON 字符串。

处理错误

在使用 Fetch API 时,网络错误和 HTTP 状态码都会导致 Promise 被拒绝。在处理响应时,我们可以通过检查状态码来决定怎么处理错误:

1
2
3
4
5
6
7
8
9
10
11
12
13
fetch('https://jsonplaceholder.typicode.com/nonexistent')
.then(response => {
if (!response.ok) {
throw new Error('请求失败,状态码: ' + response.status);
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('发生错误:', error);
});

在这个例子中,我们请求一个不存在的资源,使用 response.ok 检查响应是否成功。若失败,就抛出一个错误。

设置请求参数

有时候我们可能需要向请求中传递查询参数,可以使用 URLSearchParams API:

1
2
3
4
5
6
7
8
9
10
11
12
const params = new URLSearchParams({
userId: 1
}).toString();

fetch(`https://jsonplaceholder.typicode.com/posts?${params}`)
.then(response => response.json())
.then(data => {
console.log(data); // 处理返回的数据
})
.catch(error => {
console.error('请求失败:', error);
});

在这个例子中,我们使用 URLSearchParams 构建查询字符串,将其添加到 URL 中。

处理响应类型

除了 JSON,Fetch API 还支持处理其他类型的响应。比如,如果要获取文本响应,可以使用 response.text()

1
2
3
4
5
6
7
8
fetch('https://example.com/some-text')
.then(response => response.text())
.then(data => {
console.log('获取的文本:', data);
})
.catch(error => {
console.error('请求失败:', error);
});

总结

Fetch API 是一种强大且灵活的浏览器网络请求 API。它支持多种请求方式,简化了网络请求的过程。在处理网络请求时,记得妥善处理异常和响应状态,以提升应用的健壮性。

29 Local Storage 简介

29 Local Storage 简介

Local Storage 是一种 Web 存储机制,它可以让你在用户的浏览器中存储数据,数据不会因为页面刷新或浏览器关闭而消失。与 Session Storage 不同,Local Storage 的数据在浏览器会话之间是持久的。本文将通过示例来讲解 Local Storage 的基本用法。

Local Storage 的基本操作

存储数据

要存储数据,我们使用 setItem 方法。它接受两个参数:键(key)和值(value)。

1
2
// 存储一个用户的名字
localStorage.setItem('username', 'JohnDoe');

读取数据

要读取数据,我们使用 getItem 方法,传入要获取的键。

1
2
3
// 获取存储的用户名
const username = localStorage.getItem('username');
console.log(username); // 输出: JohnDoe

删除数据

如果你需要删除某个键值对,可以使用 removeItem 方法:

1
2
// 删除用户的名字
localStorage.removeItem('username');

清空所有数据

如果需要清空 Local Storage 中的所有数据,可以使用 clear 方法:

1
2
// 清空所有存储的数据
localStorage.clear();

针对 Local Storage 的案例

下面我们将创建一个简单的示例,展示如何使用 Local Storage 来保存用户的偏好设置。

实例:保存用户主题偏好

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="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>主题偏好设置</title>
<style>
body.light { background-color: white; color: black; }
body.dark { background-color: black; color: white; }
</style>
</head>
<body>
<h1>选择你的主题</h1>
<button id="lightBtn">浅色主题</button>
<button id="darkBtn">深色主题</button>

<script>
// 检查并应用用户的主题偏好
const currentTheme = localStorage.getItem('theme');
if (currentTheme) {
document.body.className = currentTheme;
}

// 设置浅色主题
document.getElementById('lightBtn').onclick = function() {
document.body.className = 'light';
localStorage.setItem('theme', 'light');
}

// 设置深色主题
document.getElementById('darkBtn').onclick = function() {
document.body.className = 'dark';
localStorage.setItem('theme', 'dark');
}
</script>
</body>
</html>

在这个例子中,我们有两个按钮让用户选择主题。根据用户的选择,Local Storage 会保存他们的偏好设置。每次加载页面时,我们检查 Local Storage 中是否有已保存的主题,并应用它。

Local Storage 的注意事项

  1. 存储大小限制:大多数浏览器对 Local Storage 的大小限制在 5MB 左右。
  2. 数据类型Local Storage 只能存储字符串。如果需要保存对象或数组,需使用 JSON.stringify(),将对象转换为字符串进行存储,取出时使用 JSON.parse() 恢复。

示例:存储对象

1
2
3
4
5
6
7
// 存储用户信息对象
const user = { name: 'JohnDoe', age: 30 };
localStorage.setItem('user', JSON.stringify(user));

// 读取用户信息
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log(storedUser); // 输出: { name: 'JohnDoe', age: 30 }

结语

Local Storage 是一种强大的工具,用于在客户端持久保存数据。通过简单的 API 你可以方便地存取小量数据,提升用户体验。希望通过本节的内容和案例,你能够更好地理解和使用 Local Storage

30 Session Storage 使用指南

30 Session Storage 使用指南

Session Storage 是一个非常实用的 Web API,允许在用户会话的浏览器窗口中存储数据。与 Local Storage 不同,Session Storage 仅在当前的会话中有效,即窗口或标签页关闭后数据将被清除。

1. 什么是 Session Storage?

Session Storage 是根据用户的会话创建的键值对存储。当浏览器窗口或标签页关闭时,存储在 Session Storage 中的数据会被删除。使用 Session Storage 可以有效地存储临时数据。

2. Session Storage 的基本操作

2.1 设置数据

使用 setItem 方法可以向 Session Storage 中存储数据。数据需要以 keyvalue 的形式进行存储。

1
2
// 存储用户姓名
sessionStorage.setItem('username', 'JohnDoe');

2.2 获取数据

使用 getItem 方法可以从 Session Storage 中获取数据。

1
2
3
// 获取并打印用户姓名
const username = sessionStorage.getItem('username');
console.log(username); // 输出: JohnDoe

2.3 删除数据

使用 removeItem 方法可以删除特定的存储项。

1
2
// 删除用户姓名
sessionStorage.removeItem('username');

2.4 清空所有数据

使用 clear 方法可以清空 Session Storage 中的所有数据。

1
2
// 清空 Session Storage
sessionStorage.clear();

3. 案例:使用 Session Storage 记住用户选择

下面是一个简单的示例,展示如何使用 Session Storage 记录用户选择的主题。

3.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Session Storage 示例</title>
<style>
body.light {
background-color: #f0f0f0;
color: #000;
}
body.dark {
background-color: #333;
color: #fff;
}
</style>
</head>
<body>
<h1>选择主题</h1>
<button id="light-button">浅色主题</button>
<button id="dark-button">深色主题</button>

<script src="script.js"></script>
</body>
</html>

3.2 JavaScript 逻辑

script.js 文件中我们将添加逻辑来保存和加载用户的主题选择。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 当页面加载时,检查 Session Storage 中是否有主题信息
window.onload = function() {
const savedTheme = sessionStorage.getItem('theme');
if (savedTheme) {
document.body.className = savedTheme; // 应用保存的主题
}
};

// 设置浅色主题
document.getElementById('light-button').onclick = function() {
document.body.className = 'light'; // 修改 body 的类名
sessionStorage.setItem('theme', 'light'); // 保存到 Session Storage
};

// 设置深色主题
document.getElementById('dark-button').onclick = function() {
document.body.className = 'dark'; // 修改 body 的类名
sessionStorage.setItem('theme', 'dark'); // 保存到 Session Storage
};

4. 注意事项

  • Session Storage 的容量通常为 5MB,但具体大小可能因浏览器而异。
  • 只能存储字符串类型的数据。如果需要存储对象,您需要使用 JSON.stringify 进行转换;取出数据时使用 JSON.parse 进行解析。
1
2
3
4
5
6
7
// 存储对象
const user = { name: 'Jane', age: 25 };
sessionStorage.setItem('user', JSON.stringify(user));

// 获取并解析对象
const retrievedUser = JSON.parse(sessionStorage.getItem('user'));
console.log(retrievedUser.name); // 输出: Jane

通过这些基本用法和实际案例,您可以在项目中有效地利用 Session Storage 来管理临时数据。