Ajax+axios案例

Ajax+axios案例

API地址:https://v1.jinrishici.com/

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
    <button id="btn">发送请求</button>
    <h3 id="title"></h3>
    <script>
      var btn = document.getElementById("btn")
      var title = document.getElementById("title")
      // 原生XMLHttpRequest
      btn.onclick = function () {
        var xhr = new XMLHttpRequest()
        xhr.open("get", "https://v1.jinrishici.com/shuqing/aiguo")
        xhr.send()
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            // 获取服务器响应的数据
            console.log(xhr.responseText)
            var rt = JSON.parse(xhr.responseText)
            console.log(rt)
            title.innerText = rt.content
          }
        }
      }
      // axios请求
      //btn.onclick = function () {
      //  const a = axios.get("https://v1.jinrishici.com/shuqing/aiguo").then(
      //          res => {
      //              console.log(res)
      //              // title.innerText = res.data.content
      //          }
      //  ).catch(
      //              err => {
      //                  console.log(err)
      //              }
      //  )
      //}
      // 基于jq的Ajax请求
      //btn.onclick = function () {
      //  $.ajax({
      //    method:'get',
      //    url:"https://v1.jinrishici.com/shuqing/aiguo",
      //    success:function (res) {
      //      console.log(res)
      //
      //      title.innerText = res.content
      //    },
      //    error: function (err) {
      //      console.log(err)
      //    }
      //  })
      //}
    </script>
</body>
</html>
相关推荐
小白学习日记1 小时前
【复习】HTML常用标签<table>
前端·html
学习使我快乐011 小时前
AJAX 2——Bootstrap弹框使用、图书管理案例、图片上传方法
ajax·okhttp·bootstrap
丁总学Java1 小时前
微信小程序-npm支持-如何使用npm包
前端·微信小程序·npm·node.js
yanlele2 小时前
前瞻 - 盘点 ES2025 已经定稿的语法规范
前端·javascript·代码规范
懒羊羊大王呀2 小时前
CSS——属性值计算
前端·css
DOKE2 小时前
VSCode终端:提升命令行使用体验
前端
xgq2 小时前
使用File System Access API 直接读写本地文件
前端·javascript·面试
用户3157476081352 小时前
前端之路-了解原型和原型链
前端
永远不打烊2 小时前
librtmp 原生API做直播推流
前端
北极小狐2 小时前
浏览器事件处理机制:从硬件中断到事件驱动
前端