学习fetch API
需要对Promise和Arrow Function有一些了解
源代码:
<!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>Fetch API Sanbox</title>
</head>
<body>
<button id="getText">Get Text</button>
<button id="getUsers">Get JSON</button>
<button id="getPosts">Get API DATA</button>
<hr>
<div id="output"></div>
<form action="" id="addPosts">
<div>
<input type="text" id="title" placeholder="Title">
</div>
<div>
<textarea id="body" placeholder="Body"></textarea>
</div>
<input type="submit" value="Submit">
</form>
</body>
<script>
//To learn this, you‘d better familiar with..
// * arrow function
// * promise
document.getElementById(‘getText‘)
.addEventListener(‘click‘, getText);
document.getElementById(‘getUsers‘)
.addEventListener(‘click‘, getUsers);
document.getElementById(‘getPosts‘)
.addEventListener(‘click‘, getPosts);
document.getElementById(‘addPosts‘)
.addEventListener(‘submit‘, addPosts);
function getText() {
// console.log(123);
// fetch(‘sample.txt‘)
// .then( function(res){
// return res.text(); //promise
// })
// .then(function(data){
// console.log(data);
// });
/* much cleaner way */
fetch(‘sample.txt‘)
.then((res) => res.text())
.then((data) => {
document.getElementById(‘output‘).innerHTML = data;
})
.catch((err) => console.log(err));
}
function getUsers() {
fetch(‘users.json‘)
.then((res) => res.json())
.then((data) => {
let output = ‘<h2>Users</h2>‘;
data.forEach(function (user) {
output += `
<ul>
<li>ID: ${user.id}</li>
<li>Name: ${user.name}</li>
<li>:Email: ${user.email}</li>
</ul>
`;
});
document.getElementById(‘output‘).innerHTML = output;
})
}
function getPosts() {
fetch(‘https://jsonplaceholder.typicode.com/posts‘)
.then((res) => res.json())
.then((data) => {
let output = ‘<h2>Posts</h2>‘;
data.forEach(function (post) {
output += `
<div>
<h3>${post.title}</h3>
<p>${post.body}</p>
</div>
`;
});
document.getElementById(‘output‘).innerHTML = output;
})
}
function addPosts(e) {
e.preventDefault();
let title = document.getElementById(‘title‘).value;
let body = document.getElementById(‘body‘).value;
fetch(‘https://jsonplaceholder.typicode.com/posts‘, {
method: ‘POST‘,
headers: {
‘Accept‘: ‘application/json, text/plain, */*‘,
‘Content-type‘: ‘application/json‘
},
body: JSON.stringify({ title: title, body: body })
})
.then((res) => res.json())
.then((data) => console.log(data));
}
</script>
</html>