Fetch APIs
Fetch Api is a new ajax solution, Fetch will return Promise; Fetch is not a further encapsulation of ajax, but native js, without using XMLHttpRequest object.
The technology of data interaction between the front-end and the back-end has been updated, and the original XMLHttpRequest object has been accepted by AJAX operations, but we know that the API design of the XMLHttpRequest object is not very good, and the input, output, and status are all managed in the same interface. It is easy to write very messy code.
Then the Fetch API was born, providing a new specification to replace the imperfect XMLHttpRequest object.
Fetch Api has two main features
One is interface rationalization. AJAX puts all interfaces of different nature on XHR objects, while Fetch distributes them on several different objects, which makes the design more reasonable; the second is that Fetch operation returns Promise objects, avoiding nesting callback function.
Fetch Api request 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"}
]
Note: Please open the http service and visit index.html
Demo
author
Author:TANKING
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。