码迷,mamicode.com
首页 > Windows程序 > 详细

fetch API

时间:2018-03-15 19:15:36      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:mit   turn   viewport   char   function   rom   reac   ISE   textarea   

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

标签:mit   turn   viewport   char   function   rom   reac   ISE   textarea   

原文地址:https://www.cnblogs.com/eret9616/p/8575216.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!