axios的使用规范

axios的使用规范

axios在线库:https://unpkg.com/axios/dist/axios.min.js

获取网络请求

get格式

axios.get(地址?key=value&key2=value2).then(function(response){},function(err){})
//地址为接口地址,key是文档提供,then在请求完成时触发,参数response用来获取请求信息,第二个方法function会在请求失败时触发,err用来获取错误信息

post格式

axios.post(地址,{key:value,key2:value2}).then(function(response){},function(err){})
//地址为接口地址,key是文档提供,then在请求完成时触发,参数response用来获取请求信息,第二个方法function会在请求失败时触发,err用来获取错误信息

如下例题

功能:点击get获取一个6个笑话,点击post添加添加用户名。

<body>
    <script src="https://unpkg.com/axios/dist/axios.min.js" integrity="sha384-+NRdXivfZOkeos9sVbI4eTjBbSpQirDT5tE3uF/gKVNoXQhIjP3+de6yIEVGeTCG" crossorigin="anonymous"></script> 
    
    <input type="button" class="get" value="get">
    <input type="button" class="put" value="post">

    <script>
document.querySelector(".get").onclick=function(){
    axios.get("https://autumnfish.cn/api/joke/list?num=6")
    .then(function(response){
        console.log(response);
    },function(err){
        console.log(err)
    }) 
}

 document.querySelector(".put").onclick=function(){
    axios.post("https://autumnfish.cn/api/user/reg",{username:"小h"})
    .then(function(response){
        console.log(response);
    },
    function(err){
        console.log(err);
    })
 }
    </script>
</body>

Vue和axios结合使用

格式:

var app=new Vue({
    el:"#app",
    data:{
        info:""
    },
  methods:{
      gets:function(){
          var ths=this;   //把this用变量存放起来,防止this在axios中改变
         axios.get(API链接)
         .then(function(respons){
             console.log(respons);
         },
         function(err){
             console.log(err);  //输出错误信息
         })
      }
  }
})

例子

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js" integrity="sha384-t1tHLsbM7bYMJCXlhr0//00jSs7ZhsAhxgm191xFsyzvieTMCbUWKMhFg9I6ci8q" crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js" integrity="sha384-+NRdXivfZOkeos9sVbI4eTjBbSpQirDT5tE3uF/gKVNoXQhIjP3+de6yIEVGeTCG" crossorigin="anonymous"></script>
<body>
    <div id="app">
    <input type="button" @click="gets" value="获取笑话">
      <p>{{info}}</p>    <!--存放笑话的变量-->
    <div>

    <script> 
   var app=new Vue({
       el:"#app",
       data:{
           info:""
       },
     methods:{
         gets:function(){
             var ths=this;   //把this用变量存放起来,防止this在axios中改变
            axios.get("https://autumnfish.cn/api/joke")
            .then(function(respons){
                ths.info=respons.data;   //用存有this的变量代替this
                console.log(respons.data);
            },
            function(err){
                console.log(err);  //输出错误信息
            })
         }
     }
   })
    </script>
</body>
posted @ 2022-03-29 23:11  永恒之月TEL  阅读(48)  评论(0编辑  收藏  举报