Fetch API
get from txt
fetch内置promise,使用then实现asynchronous;
catch抓取fetch中出现的error;
document.getElementById('button1').addEventListener('click',getText);
function getText(){
fetch('test.txt')
.then(function(res){
//console.log(res);
return res.text();
})
.then(function(data){ //前面return的
console.log(data);
document.getElementById('output').innerHTML=data;
})
.catch(function(err){
console.log(err);
});
}
get from JSON
//get local json data
function getJson(){
fetch('post.json')
.then(function(res){
//console.log(res);
return res.json();
})
.then(function(data){ //前面return的
console.log(data);
let output="";
data.forEach(function(post){
output+=`<li>${post.title}</li>`;
});
document.getElementById('output').innerHTML=output;
//document.getElementById('output').innerHTML=data;
})
.catch(function(err){
console.log(err);
});
}
get from API
//get from external API
function getExternal(){
fetch('https://api.github.com/users')
.then(function(res){
//console.log(res);
return res.json();
})
.then(function(data){ //前面return的
console.log(data);
let output="";
data.forEach(function(user){
output+=`<li>${user.login}</li>`;
});
document.getElementById('output').innerHTML=output;
//document.getElementById('output').innerHTML=data;
})
.catch(function(err){
console.log(err);
});
}