<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>
<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>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号