后端发出请求,前端进行接收(AJAX)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style>
        #result {
            width: 300px;
            height: 100px;
            border: 1px solid red;
        }
        </style>
    </head>
    <body>
        <div id="result"></div>
    </body>
    <script type="text/javascript">
    //获取元素
        const result = document.getElementById('result');
    //绑定键盘按下事件
      window.onkeydown = function(){
          //发送请求
          const xhr = new XMLHttpRequest();
          //设置响应体数据类型
          xhr.responseType = 'json';
          //初始化
          xhr.open('GET','http://127.0.0.1:8000/json-server');
          //发送
          xhr.send();
          //事件绑定1
          xhr.onreadystatechange = function() {
              if(xhr.readyState === 4) {
                if(xhr.status >= 200 && xhr.status < 300){
                    //手动获取数据
                    // let data = JSON.parse(xhr.response);
                    // console.log(data)
                    // result.innerHTML = data.name;
                     
                     
                    //自动获取数据  使用方法:xhr.responseType = 'json';
                    console.log(xhr.response)
                     let data = xhr.response
                    result.innerHTML = data.name;
                     
                }
              }
          }
      }
    </script>
</html>

  

 

posted on   爱前端的小魏  阅读(32)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 提示词工程——AI应用必不可少的技术
· 地球OL攻略 —— 某应届生求职总结
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界
历史上的今天:
2022-02-07 iframe框架
2022-02-07 html标签--总结大全
2022-02-07 html和xhtml的区别

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示