fetch API

学习fetch API。

 

总结:

fetch('sample.txt').then((res)=>{

     //这里返回的是一个http响应body

     console.log(res);

 

 

 

   

Body 类定义了以下方法 (这些方法都被 Request 和Response所实现)以获取body内容. 这些方法都会返回一个被解析后(也就是说已经被resolve()或者reject()并被解析成相应特定格式的东西了,所以可以被then!!)的promise对象和数据.

  • arrayBuffer()
  • blob()
  • json()
  • text()
  • formData()

所以fetch('sample.txt').then((res)=>{return res}).then((res)=>{  console.log(res.text())  });

//以上是一个简单的介绍

})

 

 

我个人理解是对XHR的简化,

因为XmlHttpRequest在原生中要写好长好长,

出现JQuery这种可以简化的写法,如果原生带了Fetch,那么就简化了好多好多。

 

*学习Fetch需要对Promise和Arrow Function有一些了解

 

 

备注:请打开live-server进行测试。 

 

源代码:(请粘贴到VSCode中学习)

<!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>

 

 

 

文件:

sample.txt:

I am a sample text file

 

users.json:

[{
"id":0,
"name":"rick",
"email":"rick@gmail.com"
},
{
"id":2,
"name":"Glenn",
"email":"glenn@gmail.com"
},
{
"id":3,
"name":"Negan",
"email":"negan@gmail.com"
}]

 

posted @ 2018-03-15 18:05  hh9515  阅读(155)  评论(0编辑  收藏  举报