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>
相关推荐
小小小小宇2 小时前
前端 Service Worker
前端
只喜欢赚钱的棉花没有糖2 小时前
http的缓存问题
前端·javascript·http
小小小小宇2 小时前
请求竞态问题统一封装
前端
loriloy2 小时前
前端资源帖
前端
源码超级联盟2 小时前
display的block和inline-block有什么区别
前端
GISer_Jing3 小时前
前端构建工具(Webpack\Vite\esbuild\Rspack)拆包能力深度解析
前端·webpack·node.js
让梦想疯狂3 小时前
开源、免费、美观的 Vue 后台管理系统模板
前端·javascript·vue.js
海云前端3 小时前
前端写简历有个很大的误区,就是夸张自己做过的东西。
前端
葡萄糖o_o3 小时前
ResizeObserver的错误
前端·javascript·html
AntBlack3 小时前
Python : AI 太牛了 ,撸了两个 Markdown 阅读器 ,谈谈使用感受
前端·人工智能·后端