index.html 调用 ajax

index.html

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>AJAX 请求示例</title>
  <script>
    // 封装 Ajax 为公共函数:传入回调函数 success 和 fail
    function myAjax (url, success, fail) {
      // 1、创建XMLHttpRequest对象
      var xmlhttp
      if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest()
      } else {
        // 兼容IE5、IE6浏览器。不写也没关系
        xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
      }
      // 2、发送请求
      xmlhttp.open('GET', url, true)
      xmlhttp.send()
      // 3、服务端响应
      xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
          var obj = JSON.parse(xmlhttp.responseText)
          console.log('数据返回成功:' + obj)
          success && success(xmlhttp.responseText)
        } else {
          // 这里的 && 符号,意思是:如果传了 fail 参数,就调用后面的 fail();如果没传 fail 参数,就不调用后面的内容。因为 fail 参数不一定会传。
          fail && fail(new Error('接口请求失败'))
        }
      }
    }

    // 单次调用 ajax
    function singleAjaxCall () {
      myAjax('a.json', (res) => {
        console.log('单次调用结果:', res)
      }, (err) => {
        console.error('单次调用失败:', err)
      })
    }

    // 多次调用 ajax。接口请求顺序:a --> b --> c
    function multipleAjaxCalls () {
      myAjax('a.json', (res) => {
        console.log('a.json 结果:', res)
        myAjax('b.json', (res) => {
          console.log('b.json 结果:', res)
          myAjax('c.json', (res) => {
            console.log('c.json 结果:', res)
          }, (err) => {
            console.error('c.json 请求失败:', err)
          })
        }, (err) => {
          console.error('b.json 请求失败:', err)
        })
      }, (err) => {
        console.error('a.json 请求失败:', err)
      })
    }

    window.onload = function () {
      singleAjaxCall()
      multipleAjaxCalls()
    };
  </script>
</head>

<body>
  <h1>AJAX 请求示例</h1>
</body>

</html>

创建 JSON 文件

a.json

html 复制代码
{
    "message": "这是 a.json 的数据"
}

b.json

html 复制代码
{
    "message": "这是 b.json 的数据"
}

c.json

html 复制代码
{
    "message": "这是 c.json 的数据"
}

启动 HTTP 服务器

确保所有文件都在同一个目录下,然后启动 HTTP 服务器。

html 复制代码
python -m http.server 8000

访问 HTML 文件

html 复制代码
http://localhost:8000/index.html
相关推荐
前端老鹰6 小时前
HTML <meta name="color-scheme">:自动适配系统深色 / 浅色模式
前端·css·html
全宝9 小时前
🚀前端必学!告别样式冲突:Shadow DOM 终极指南
前端·javascript·html
Viking_bird1 天前
Apache Spark 3.2.0 开发测试环境部署指南
大数据·分布式·ajax·spark·apache
前端老鹰1 天前
CSS backdrop-filter:给元素背景添加模糊与色调的高级滤镜
前端·css·html
杨超越luckly1 天前
HTML应用指南:利用POST请求获取上海黄金交易所金价数据
前端·信息可视化·金融·html·黄金价格
前端程序猿i1 天前
用本地代理 + ZIP 打包 + Excel 命名,优雅批量下载跨域 PDF
前端·javascript·vue.js·html
遗悲风1 天前
html二次作业
前端·html
中草药z1 天前
【自动化测试】Selenium详解-WebUI自动化测试
前端·功能测试·selenium·自动化·html·web·测试
步行cgn2 天前
在 HTML 表单中,name 和 value 属性在 GET 和 POST 请求中的对应关系如下:
前端·hive·html
找不到工作的菜鸟2 天前
Three.js三大组件:场景(Scene)、相机(Camera)、渲染器(Renderer)
前端·javascript·html