【Ajax】发送get请求获取接口数据

编写html实现通过Ajax发送get请求并获取数据

代码实现
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Index</title>
</head>
<body>
    <br>
    <h2 style="text-align: center;">获取数据</h2>
    <div style="text-align: center;">
        <input type="button" value="获取" onclick="getData()" />
        <div id="textArea">

        </div>
    </div>
</body>
<script>
    function getData(){
        // 创建请求
        var xhttp = new XMLHttpRequest();
        // 定义请求
        xhttp.open("GET", "https://mock.apifox.cn/m1/3038469-0-default/emp/list", true)
        // 回调函数,执行完请求后,会将数据返回来
        xhttp.onreadystatechange = function(){
            if(this.readyState == 4 && this.status == 200){
                // this.responseText发送请求后,响应过来的数据
                document.getElementById("textArea").innerHTML = this.responseText;
            }
        };
        // 发送请求
        xhttp.send();
    }
</script>
</html>
结果
  • 运行编写好的html页面,点击获取数据按钮,即可获取到对应接口返回的数据
相关推荐
NiceCloud喜云8 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby8 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
丷丩8 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
Front思9 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
ZC跨境爬虫11 小时前
跟着 MDN 学CSS day_29:(掌握文本与字体样式的核心艺术)
前端·css·ui·html·tensorflow
李子琪。12 小时前
网络空间安全深度实战:CSRF 漏洞原理剖析与基于 Token 的纵深防御体系构建(全栈实验报告)
前端·安全·csrf
冰暮流星12 小时前
javascript之history对象介绍
前端·笔记
IT_陈寒12 小时前
Vite热更新失灵?你可能漏了这个配置
前端·人工智能·后端
丷丩12 小时前
MapLibre GL JS第19课:实时更新要素
前端·javascript·gis·map·mapbox·maplibre gl js
Mr.Daozhi12 小时前
RAG 进阶实战:跑通 Demo 后我连续翻了 6 次车,逐一修复才真正可用(含 Gradio Web 版)
前端·数据库·langchain·大模型·gradio·rag·科研工具