Fetch Api
Fetch Api是新的ajax解决方案,Fetch会返回Promise;Fetch不是ajax的进一步封装,而是原生js,没有应用XMLHttpRequest对象。
前端与后端交互数据的技术始终在更新,而最后的XMLHttpRequest对象始终被AJAX操作所承受,然而咱们晓得,XMLHttpRequest对象的API设计并不是很好,输出、输入、状态都在同一个接口治理,容易写出十分凌乱的代码。
那么Fetch API就应势而生,提供了一种新标准,用来取代善不完满的 XMLHttpRequest 对象。
Fetch Api次要有两个特点
一是接口合理化,AJAX是将所有不同性质的接口都放在XHR对象上,而Fetch是将它们扩散在几个不同的对象上,设计更正当;二是Fetch操作返回Promise对象,防止了嵌套的回调函数。
Fetch Api申请Json
index.html
<!DOCTYPE html><html><head> <title>fetch示例</title> <meta charset="utf-8"> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script></head><body> <div id="songs"></div> <script type="text/javascript"> window.onload = function(){ fetch('data.json') .then(response => response.json()) .then(data => { for(var i in data){ console.log(data[i].songName) // 创立一个p标签 var p=document.createElement("p"); // 为p标签设置class p.setAttribute("class","songName"); // 向p标签渲染数据 p.innerHTML = data[i].singerName+' - '+data[i].songName; // 抉择p标签的上一级元素 var div=document.getElementById("songs"); // 将p标签增加到上一级元素外面 div.appendChild(p); } }) .catch(err => console.error(err)); } </script></body></html>
data.json
[ {"songName":"七里香","singerName":"周杰伦","headimg":"https://y.qq.com/music/photo_new/T001R150x150M0000025NhlN2yWrP4.jpg?max_age=2592000"}, {"songName":"孤勇者","singerName":"陈奕迅","headimg":"https://y.qq.com/music/photo_new/T002R300x300M000001uaPM93kxk1R_3.jpg?max_age=2592000"}, {"songName":"有何不可","singerName":"许嵩","headimg":"https://y.qq.com/music/photo_new/T001R150x150M000000CK5xN3yZDJt.jpg?max_age=2592000"}, {"songName":"一路生花","singerName":"温奕心","headimg":"https://y.qq.com/music/photo_new/T002R300x300M000001MyK3Y47zLur_2.jpg?max_age=2592000"}, {"songName":"晚风心里吹","singerName":"阿梨粤","headimg":"https://y.qq.com/music/photo_new/T002R300x300M000001whii43nuvNe_2.jpg?max_age=2592000"}]
留神:请开启http服务后拜访index.html
Demo
作者
Author:TANKING