123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- <!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>Document</title>
- </head>
- <body>
- <h1>AJAX测试</h1>
- <hr>
- <button id="btn">点击加载数据</button>
- <div id="root"></div>
- <script>
- const btn = document.getElementById("btn")
- const root = document.getElementById("root")
- btn.onclick = () =>{
- //创建一个xhr对象
- const xhr = new XMLHttpRequest()
- //设置响应体的类型,设置后会自动对数据进行类型转换
- xhr.responseType = "json"
- //可以为xhr对象绑定一个load事件
- //表示xhr中的数据加载完成以后,function()才会执行
- xhr.onload = function(){
- //xhr.status 表示响应状态码
- //console.log(xhr.status);
- if(xhr.status === 200){
- //xhr.response 表示响应信息
- //方式一:收到转换
- // const result = JSON.parse(xhr.response)
- // console.log(result.status,result.data)
- //方式二:创建完xhr对象后,设置xhr.responseType = "json"
- //读取响应信息
- //console.log(xhr.response);
- const result = xhr.response
- //判断数据是否正确
- if(result.status == "ok"){
- //创建一个ul
- const ul = document.createElement("ul")
- //将ul插入到root中
- root.appendChild(ul)
- //遍历数据
- for(let stu of result.data){
- ul.insertAdjacentHTML("beforeend",`<li>${stu.id} - ${stu.name} - ${stu.age} - ${stu.gender} - ${stu.address}</li>`)
- }
- }
- }
-
- }
-
- //设置请求信息
- xhr.open("get","http://localhost:3000/students")
- //发送请求
- xhr.send()
- }
- </script>
- </body>
- </html>
|