fetch(1)基本请求

目录结构:

fetch(1)基本请求

 

 读取文本数据

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script>
    window.onload = function() {
      let obtn = document.getElementById('btn1')
      obtn.onclick = async function() {
        // 1.请求
        let res = await fetch('data/1.txt')
        // 2.解析文本数据
        let data = await res.text()
        console.log(data)
      }
    }
  </script>
</head>
<body>
  <input type="button" value="读取" id="btn1">
</body>
</html>

 

读取json数据

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script>
    window.onload = function() {
      let obtn = document.getElementById('btn1')
      obtn.onclick = async function() {
        // 1.请求
        let res = await fetch('data/1.json')
        // 2.解析json数据
        let data = await res.json()
        console.log(data)
      }
    }
  </script>
</head>
<body>
  <input type="button" value="读取" id="btn1">
</body>
</html>

 

读取二进制数据

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script>
    window.onload = function() {
      let obtn = document.getElementById('btn1')
      let oImg = document.getElementById('img1')
      obtn.onclick = async function() {
        // 1.请求
        let res = await fetch('data/123.jpg')
        // 2.解析 图片 数据
        let data = await res.blob();
        let url = URL.createObjectURL(data);
        console.log(url) // blob:http://localhost/af62b20b-7964-47ab-8fd3-a40f4de2d5f8
        oImg.src = url;
      }
    }
  </script>
</head>
<body>
  <input type="button" value="读取" id="btn1">
  <img id="img1" />
</body>
</html> 

 

上一篇:js基础练习-倒计时


下一篇:JavaScript小练习1-控制div属性