axios 的请求方式

1.绑定点击事件 get请求无参数
复制代码
</head>

  <body>
    <h2>get请求+参数换地</h2>
    <button class="btn1">测试</button>
    <button class="btn2">测试有参数</button>
    <!-- <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> -->
    <script src="./lib/axios.js"></script>
    <script>
      // 1.绑定点击事件 get请求无参数
      const btn = document.querySelector(".btn1");
      btn.addEventListener("click", function () {
        // 请求方式1
        // axios({
        //   method: "get",
        //   url: "http://ajax-api.itheima.net/api/news",
        // })
        // 请求方2 axios.get("http://ajax-api.itheima.net/api/news")
        axios
          .get("http://ajax-api.itheima.net/api/news")
          .then(function (res) {
            console.log("返回接口成功时的结果");
          })
          .catch(function (err) {
            console.log("返回接口失败时的结果");
            console.log();
          });
      });
     </script>
  </body>
复制代码
// 2.绑定点击事件 get请求有参数
复制代码
</head>

  <body>
    <h2>get请求+参数换地</h2>
    <button class="btn1">测试</button>
    <button class="btn2">测试有参数</button>
    <!-- <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> -->
    <script src="./lib/axios.js"></script>
    <script>
   2.绑定点击事件 get请求有参数
      const btn2 = document.querySelector(".btn2");
      btn2.addEventListener("click", function () {
        // 请求携带参数的方法1URL地址后面直接拼接?属性名=属性值
        // axios.get("http://ajax-api.itheima.net/api/robot?spoken=你是谁")
//参数写在“”号里面 多个参数用&隔开
如axios.get("http://ajax-api.itheima.net/api/robot?属性名=属性值&属性名1=属性名2")
// 请求携带参数的方法2
如axios .get("http://ajax-api.itheima.net/api/robot",
{params: { spoken(属性名): "你喜欢谁?(属性值)", },})
多个参数,号隔开写在params:{写这}里面
axios .get("http://ajax-api.itheima.net/api/robot", { params: { spoken: "你喜欢谁?", }, }) .then(function (res) { console.log(res); }) .catch(function (err) { console.log("出错"); }); }); </script> </body>
复制代码

 

posted @   噢噢噢J  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示