异步函数
<script>
// ajax: 异步请求 XMLHttpRequest: xhr对象 永别了, XMLHttpRequest
// promise: 期约,它是一个对象, 用来表示"异步"操作的结果
// 实际工作中, 并不会直接用promise,而是用fetch api进行异步请求
// console.log(fetch("https://php.cn/"));
// 浏览器默认是禁止通过脚本发起一个跨域请求
// console.log(fetch("demo6.html"));
// fetch(url).then(响应回调).then(结果处理)
// console.log(1);
// 这说明这个fetch是一个异步任务,加到了异步任务队列中
// 将返回的"流格式"转为json
// fetch("data.json")
// .then((response) => response.json())
// .then((json) => console.log(json));
// console.log(3);
// 大家做测试的时候,可以选择一些提供json测试数据的网站
// fetch("https://jsonplaceholder.typicode.com/todos/5")
// .then(response => response.json())
// .then(data => console.log(data));
// 异步函数,返回 promise
// async function f1() {
// return await console.log("aaaa");
// }
// console.log(1);
// f1();
// console.log(2);
</script>
fetch api案例
<body>
<button onclick="getList()">查看留言列表</button>
<div id="box">
<!-- 这里显示全部的留言信息 -->
</div>
<script>
async function getList() {
// 请求500条留言
const response = await fetch("https://jsonplaceholder.typicode.com/comments");
const comments = await response.json();
// console.log(comments);
// 将所有数据渲染到页面中
render(comments);
}
function render(data) {
const box = document.querySelector("#box");
// 有序列表
const ol = document.createElement("ol");
data.forEach(item => {
console.log(item);
const li = document.createElement("li");
li.textContent = item.body.slice(0, 120) + "...";
// textContent: 只支持纯文本
// innerHTML: 支持html标签,并解析
li.innerHTML = `<span style="color:green">${item.body.slice(0, 120)} ...</span><hr>`;
ol.append(li);
});
box.append(ol);
}
</script>
</body>
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!