123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Fetch</title>
- <style>
- table{
- border-collapse: collapse;
- width: 50%;
- }
- td,th{
- font-size: 20px;
- text-align: center;
- border: 1px solid #000;
- }
- caption{
- font-size: 30px;
- font-weight: bold;
- }
- </style>
- </head>
- <body>
- <h1>AJAX测试</h1>
- <hr>
- <button id="btn">点击加载数据</button>
- <br><br>
- <button id="btn02">点击加载数据2</button>
- <hr>
- <div id="root"></div>
- <script>
- const btn = document.getElementById("btn")
- const btn2 = document.getElementById("btn02")
- const root = document.getElementById("root")
- btn2.onclick = () =>{
- fetch("http://localhost:3000/students",{
- method:"post",
- //请求头,主要是告诉服务器,body的内容的类型是什么
- headers:{
- "Content-type":"application/json"
- //还有一种形式是application/x-www-form-urlencoded
- },
- //请求体
- //JSON.stringify:将对象转换成json来传送
- //通过body去发送数据时,必须通过请求头来指定数据的类型
- body:JSON.stringify({
- name:"白骨精",
- age:16,
- gender:"女",
- address:"白骨洞"
- })
- //body:"name=孙悟空&age=……"
- })
- }
- btn.onclick = () =>{
- /*
- fetch:
- -fetch是xhr的升级版,采用的是Promise API
- -作用和AJAX是一样的,但是使用起来更加友好
- -fetch是原生js就支持的一种ajax请求的方式
- */
- fetch("http://localhost:3000/students")
- //不管响应状态码是多少,只要服务器响应回来以后,then就会执行
- .then((res)=>{
- if(res.status === 200){
- //res.json() 可以用来读取json格式的数据,返回的是一个promise
- //console.log(res.json());
- //在then里面只要出现了promise,直接使用return返回
- return res.json()
- }else{
- throw new Error("加载失败!")
- //then里面无论出现什么异常,都可以抛错,最后在catch里面统一处理
- }
- })
- //上一步的返回值会返回到下一步,所以此处的then相当于是读取promise的数据
- .then(res=>{
- //console.log(res);
- //获取到数据后,将数据渲染到页面中
- if(res.status == "ok"){
- //创建一个table
- const table = document.createElement("table")
- root.appendChild(table)
- table.insertAdjacentHTML("beforeend","<caption>学生列表</caption>")
- table.insertAdjacentHTML("beforeend",`
- <thead>
- <tr>
- <th>学号</th>
- <th>姓名</th>
- <th>年龄</th>
- <th>性别</th>
- <th>地址</th>
- </tr>
- </thead>
- `)
- const tbody = document.createElement("tbody")
- table.appendChild(tbody)
- //遍历数据
- for(let stu of res.data){
- tbody.insertAdjacentHTML("beforeend",`
- <tr>
- <td>${stu.id}</td>
- <td>${stu.name}</td>
- <td>${stu.age}</td>
- <td>${stu.gender}</td>
- <td>${stu.address}</td>
- </tr>
- `)
- }
- }
- })
- .catch((err)=>{
- console.log("出错了!",err);
- })
- }
- </script>
- </body>
- </html>
|