手写ajax 请求并将获取到的图片二进制流渲染到页面上

话不多说代码附上

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport"
    content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <img id="img" alt="">
  <script>
    const xhr = new XMLHttpRequest();

    xhr.open('GET', 'https://pic2.zhimg.com/50/v2-2038cd0997d58ff893d433761b90c102_hd.webp', true);
    xhr.responseType = "blob";
    
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          let res = xhr.response 
          console.log(res)
          img.src = window.URL.createObjectURL(res); 
        }
      }
    }

    xhr.send(null);
  </script>
</body>

</html>

xhr.readyState的值
手写ajax 请求并将获取到的图片二进制流渲染到页面上
status 返回状态吗含义
手写ajax 请求并将获取到的图片二进制流渲染到页面上

上一篇:Ajax简介


下一篇:XMLHttpRequest对象解析