Ajax基本使用,ajax加vue使用

306 阅读1分钟
 <input type="button" value="get请求" class="get">
 <input type="button" value="post请求" class="post">
  1. axios必须先导入再使用
  2. 使用get或post方法即可发送对应的请求
  3. then方法中的回调函数会在请求成功或失败时触发,成功是第一个response回调函数,失败是第二个err回调函数
  4. 通过回调函数的形参可以获取响应的内容,或者错误信息
            /*
                接口:随机获取一条笑话
                请求地址:https://autumnfish.cn/api/joke
                请求方法:get
                请求参数:无
                响应内容:随机笑话
            */            
     //axios.get(地址?key=value&key2=value2).then(function(response){},function(err){})
               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);
                   })
               }
                /*
                    接口2:用户注册
                    请求地址:https://autumnfish.cn/api/user/reg
                    请求方法:post
                    请求参数:username(用户名,字符串)
                    响应内容:注册成功或失败
                */ 
      //axios.post(地址,{key:value,key2:value2}).then(function(response){},function(err){})
               document.querySelector(".post").onclick=function(){
                   axios.post("https://autumnfish.cn/api/user/reg",
                   {username:"maik"})
                   .then(function(response){
                       console.log(response);
                   }),function(err){
                       console.log(err);
                   }
               }


ajax和vue

  1. axios回调函数中this已经改变,无法访问到data中数据
  2. 把this保存起来,回调函数中直接使用保存的this即可
  3. 和本地应用的最大区别就是改变了数据来源
 /*
                接口:随机获取一条笑话
                请求地址:https://autumnfish.cn/api/joke
                请求方法:get
                请求参数:无
                响应内容:随机笑话
            */
     var vm=new Vue({
         el:'#app',
         data:{
             joke:"很好笑的笑话"
         },
         methods:{
             getJoke:function(){
                 console.log(this.joke);
                 var that=this;
                 axios.get("https://autumnfish.cn/api/joke")
                 .then(function(response){
                    //  console.log(response);
                      console.log(response.data);
                    // console.log(this.joke);                   
                     that.joke=response.data;
                 },function(err){
                     console.log(err);
                 })
             } 
         }
   })