Ajax+axios案例

打印 上一主题 下一主题

主题 551|帖子 551|积分 1653

Ajax+axios案例

API地点:https://v1.jinrishici.com/
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>Title</title>
  6.     <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
  7.     <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  8. </head>
  9. <body>
  10.     <button id="btn">发送请求</button>
  11.     <h3 id="title"></h3>
  12.     <script>
  13.       var btn = document.getElementById("btn")
  14.       var title = document.getElementById("title")
  15.       // 原生XMLHttpRequest
  16.       btn.onclick = function () {
  17.         var xhr = new XMLHttpRequest()
  18.         xhr.open("get", "https://v1.jinrishici.com/shuqing/aiguo")
  19.         xhr.send()
  20.         xhr.onreadystatechange = function () {
  21.           if (xhr.readyState === 4 && xhr.status === 200) {
  22.             // 获取服务器响应的数据
  23.             console.log(xhr.responseText)
  24.             var rt = JSON.parse(xhr.responseText)
  25.             console.log(rt)
  26.             title.innerText = rt.content
  27.           }
  28.         }
  29.       }
  30.       // axios请求
  31.       //btn.onclick = function () {
  32.       //  const a = axios.get("https://v1.jinrishici.com/shuqing/aiguo").then(
  33.       //          res => {
  34.       //              console.log(res)
  35.       //              // title.innerText = res.data.content
  36.       //          }
  37.       //  ).catch(
  38.       //              err => {
  39.       //                  console.log(err)
  40.       //              }
  41.       //  )
  42.       //}
  43.       // 基于jq的Ajax请求
  44.       //btn.onclick = function () {
  45.       //  $.ajax({
  46.       //    method:'get',
  47.       //    url:"https://v1.jinrishici.com/shuqing/aiguo",
  48.       //    success:function (res) {
  49.       //      console.log(res)
  50.       //
  51.       //      title.innerText = res.content
  52.       //    },
  53.       //    error: function (err) {
  54.       //      console.log(err)
  55.       //    }
  56.       //  })
  57.       //}
  58.     </script>
  59. </body>
  60. </html>
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

飞不高

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表