微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

手写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的值

readyState中的值的含义

status 返回状态吗含义

在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐