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);
});
}
本文详细介绍如何使用 Fetch API 从本地及远程获取数据,包括读取 txt 文件、解析 JSON 数据及调用 GitHub API。通过实际代码演示了 promise 的使用,以及如何处理 fetch 过程中的错误。
454

被折叠的 条评论
为什么被折叠?



