fetch API
2021-04-21 14:27
阅读:431
YPE html>
标签:mit turn viewport char function rom reac ISE textarea
学习fetch API
需要对Promise和Arrow Function有一些了解
源代码:
//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 = ‘
Users
‘; data.forEach(function (user) {
output += `
`;
});
document.getElementById(‘output‘).innerHTML = output;
})
}
function getPosts() {
fetch(‘https://jsonplaceholder.typicode.com/posts‘)
.then((res) => res.json())
.then((data) => {
let output = ‘
Posts
‘; data.forEach(function (post) {
output += `
${post.title}
${post.body}
`;
});
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));
}
fetch API
标签:mit turn viewport char function rom reac ISE textarea
原文地址:https://www.cnblogs.com/eret9616/p/8575216.html
上一篇:C#编写一款qq消息群发器
下一篇:C#格式规范
评论
亲,登录后才可以留言!