<!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</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/skeleton/2.0.4/skeleton.min.css">
</head>
<body>
<div class="container">
<h1>Fetch Api sandbox</h1>
<button id="button1">请求本地文本数据</button>
<button id="button2">请求本地json数据</button>
<button id="button3">请求网络接口</button>
<br> <br>
<div id="output"></div>
</div>
<script>
document.getElementById("button1").addEventListener('click',getText);
document.getElementById("button2").addEventListener('click',getJson);
document.getElementById("button3").addEventListener('click',getExternal);
// 获取本地纯文本数据
function getText () {
fetch ("text/test.txt")
.then((res) => res.text()) // 解析txt数据
.then((data) => {
console.log(data);
document.getElementById("output").innerHTML = data;
})
.catch((err) => console.log(err))
}
// 获取本地json数据
function getJson () {
fetch ("json/test.json")
.then((res) => res.json())
.then((data) => {
console.log(data);
let output = '';
data.forEach(post => {
output += `<li>${post.title}</li>`
});
document.getElementById("output").innerHTML = output;
})
.catch((err) => console.log(err))
}
// 获取网络接口数据
function getExternal () {
fetch ("http://api.github.com/users")
.then((res) => res.json())
.then((data) => {
console.log(data);
let output = '';
data.forEach((user) => {
output += `<li>${user.login}</li>`
})
document.getElementById("output").innerHTML = output;
})
.catch()
}
</script>
</body>
</html>
fet 请求三种数据类型
最新推荐文章于 2021-05-05 22:51:02 发布