fetch API

Posted eret9616

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了fetch API相关的知识,希望对你有一定的参考价值。

学习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>










































以上是关于fetch API的主要内容,如果未能解决你的问题,请参考以下文章

API Fetch 返回 nil

未定义的变量 - 虽然 api fetch |爱讯 |道具

ReactJS 从 API fetch 中获取令牌字符串

无法读取未定义的属性“mockResolvedValue”

没有通量的同构 react.js

mysql_fetch_array、mysql_fetch_assoc、mysql_fetch_object