java-web/examples/chapter03/fetch.html

57 lines
1.6 KiB
HTML
Raw Normal View History

2024-10-06 11:13:05 +08:00
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<h2 id="title"></h2>
<div id="content"></div>
</div>
</body>
<script>
const url = 'https://jsonplaceholder.typicode.com/posts/1';
// 使用 fetch 发送 GET 请求
fetch(url).then(response => {
// 检查响应状态
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// 解析 JSON 响应
return response.json();
}).then(data => {
// 处理解析后的 JSON 数据
console.log(data);
document.getElementById("title").innerHTML = data.title;
document.getElementById("content").innerHTML = data.body;
}).catch(error => {
// 处理任何发生的错误
console.error('There has been a problem with your fetch operation:', error);
});
// 发送 POST 请求并附加请求头
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST', // 或 'PUT'
headers: {
'Content-Type': 'application/json',
// 其他头部信息...
},
body: JSON.stringify({ title: 'axjax入门', body: 'abcdefghijklmn', userId: 1 }) // 转换为 JSON 字符串
}).then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}).then(data => {
console.log(data);
}).catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
</script>
</html>