fetch API简单使用方法

来源:互联网 发布:杜老师的c编程密码 编辑:程序博客网 时间:2024/06/04 23:21

fetch 可以看做是将要代替ajax的一种方式;行为与promise类似,下面是一些简单的使用方法:

<body>    <img src="" alt="">    <script>        myImage = document.querySelector('img');        fetch("./lenna.jpg")            .then(function (res) {                return res.blob()            })            .then(function (blob) {                var objectURL = URL.createObjectURL(blob);                myImage.src = objectURL;            })        fetch("./data.json")            .then(function(res){                return res.json();            })            .then(function(data){                console.log(data);            })    </script></body>

值得注意的是fetch第一个then方法的response参数并不是实际返回的数据,而是一个包含response的promise对象,所以在这一层需要格式化返回数据,并继续传递给下一层。

更详细的内容可参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

原创粉丝点击