码迷,mamicode.com
首页 > 移动开发 > 详细

axios的简单使用

时间:2017-09-28 18:09:53      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:logs   做了   简单   new   指正   method   charset   str   etl   

既然官方已经说了不在维护vue-resource,那我们就看看axios是怎么使用的..........

1)get方法的使用

axios.get
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>axios的初步使用</title>
    <script src="../lib/vue.js"></script>
    <script src="../lib/axios.min.js"></script>
</head>
<body>
   <div id="app">
       <my-f1></my-f1>
   </div>
</body>
</html>
<script>
    const c1={
        template:`
            <div v-if="userList.length">
                  <ul>
                    <li v-for="item in userList">{{item.id}}</li>
                  </ul>
            </div>
        `,
        props:{},
        data(){
            return {
                userList:[fd,rr,tt],
            }
        },
        mounted(){
            this.getList();
        },
        computed:{
             user(){
                return this.usersList;
             }
        },
        methods:{
            getList(){
                const self=this;
                axios.get(../data/a1.php,{params:{
                    id:2
                }}).then(function(res){
                    self.userList=res.data;
                }).catch(function(res){
                    console.log(res);
                });
            },
        }
    };
    const myVue = new Vue({
        el:#app,
        components:{
            myF1:c1
        },
    });
</script>

a1.php

<?php
  header("Content-Type:application/json;charset=UTF8");
  $myDB=  new PDO(mysql:host=127.0.0.1;dbname=axiox;port=3307,root,‘‘);
  $id=$_GET[id];
 //  $fname=$_POST[‘firstname‘];
  // $lname=$_POST[‘lastname‘];
  // $body = @file_get_contents(‘php://input‘);
 // echo $fname ;
  if($myDB){
     $res= $myDB->query("select * from stu");

     while($row = $res->fetch( PDO::FETCH_ASSOC)){
        // print_r($row);
        $arr[]=$row;
     }
  }
  else{
    die("fali");
  }
 // json_encode($arr);
  print_r( json_encode($arr));
?>

以上很简单的一个例子。。。。

我们注意一下请求头的content-type

技术分享

 

2)使用post请求

axios.post
当你使用post请求的时候,好像会有一点问题。。。。。
axios.post(../data/a1.php, {//后端就不能使用$_post[‘‘]接受参数了,后端要接受请求主体
name:士大夫, age:33 }) .then(function(res){ self.userList=res.data; }) .catch(function(res){ console.log(res); });

php:

$fname=$_POST[name];

技术分享

 

结果:

技术分享

好像获取不到请求传递的值......

但是办法还是有的,这个时候我们可以在后端(这里使用的是php),来获取整个请求主体....

$body = @file_get_contents(php://input);

但还是很奇怪,为啥????

看看官方的解释.................

技术分享

然后我就试试....

    getList(){
            const self=this;        //这里我们不修改请求头,而是修改 userService(手动将post请求参数变为get请求形式,后端可以使用$_POST[‘参数名‘],接受参数)
            let param = new URLSearchParams();
            param.append("firstname", "Fred");
            param.append("lastname", "Flintstone");

            axios.post(../data/a1.php,param)
            .then(function(res){
                self.userList=res.data;
            })
            .catch(function(res){
                console.log(res);
            });
            
        },

php接受参数;(很明显我前端做了参数处理

$fname=$_POST[firstname];
echo $fname;

技术分享

 技术分享

很明显的发现我们现在的请求方式变为:

Content-Type:application/x-www-form-urlencoded;charset=UTF-8
 
问题来了,我不想使用这个let param = new URLSearchParams();但是又想发送我的post请求怎么办??
 
那么就让后端做处理了
前端:(不做处理)
axios.post(../data/a2.php, {
    name:tom,
    age:33,
    id:wodo id shi 222
})
.then(function(res){
    self.userList=res.data;
})
.catch(function(res){
     console.log(res);
});

后端:

  $body = @file_get_contents(php://input);//接受整个请求主体
  $body=json_decode($body)  ;//反序列化
  $id=$body->id;//获取欲取参数
  echo $id;

 

3)axios.all的使用
我们可能要在多个请求完成之后,在进行下一步操作,这里涉及到一个异步问题,但是axios.all就可以帮我们轻松解决这个问题。。。
我本以为是这样,但是结果好像不是这样。。。。。。。。。。。。。。。。。。。
【可能是我理解有误,如果有人能指正,很感激。。】
先看看我的例子
<script>
    const c1={
        template:`
    <div v-if="userList.length">
            <ul>
            <li v-for="item in userList">{{item.id}}</li>
            <p>this is  tea ifno :
                <table>
                  <tr>
                    <td>id</td>
                    <td>name</td>
                    <td>salary</td>
                    <td>address</td>
                  </tr>
                    <tr>
                        <td>{{tea.id}}</td>
                        <td>{{tea.name}}</td>
                        <td>{{tea.salary}}</td>
                        <td>{{tea.address}}</td>
                    </tr>
                </table>
            </p>
    </ul>
    </div>
    `,
    props:{},
    data(){
        return {
            userList:[fd,rr,tt],
            tea:{},
        }

    },
    mounted(){
        axios.all([this.getList(), this.getTea()])
                .then(axios.spread(function (acct, perms) {
                     console.log("all request finished");
                     console.log(acct);
                }));
    },
    methods:{
        getList(){
            const self=this;
             axios.get(../data/a1.php)
             .then(function(res){
             self.userList=res.data;
             })
             .catch(function(res){
             console.log(res);
             });
        },

        //第二个请求
        getTea(){
            const self=this;
            axios.get(../data/a2.php,{
              params:{id:2,}
                //name:‘fafa‘
            }).then(function(res){
                self.tea =res.data[0];
            });
        }
    }
};

const myVue = new Vue({
    el:#app,
    components:{
        myF1:c1
    },
});
</script>

我在php文件中做了一个延时处理。

a2.php

<?php
  $conn=mysqli_connect(127.0.0.1,root,‘‘,axiox,3307);
  $sql="SET NAMES UTF8";
  mysqli_query($conn,$sql);

  // $body = @file_get_contents(‘php://input‘);
  //$body=json_decode($body)  ;

  //$id=$body->id;


  // $id=$_POST[‘id‘];

  $id=$_GET[id];
  $sql="SELECT * FROM tea WHERE id=$id";
  $result=mysqli_query($conn,$sql);
  $list=mysqli_fetch_assoc($result);
  $arr=[];
  $arr[]=$list;
  sleep(5);
  echo json_encode($arr);
 // print_r( json_encode($res));
?>

a1.php

<?php
  // header("Content-Type:application/json;charset=UTF8");
  // header("Content-Type:application/x-www-form-urlencoded;charset=UTF8");
  $myDB=  new PDO(mysql:host=127.0.0.1;dbname=axiox;port=3307,root,‘‘);

  //$id=$_GET[‘id‘];
  //  $lname=$_POST[‘lastname‘];
  //$body = @file_get_contents(‘php://input‘);
  //$fname=$_POST[‘firstname‘];
  //echo $body ;
  // echo $fname;

  if($myDB){
     $res= $myDB->query("select * from stu");

     while($row = $res->fetch( PDO::FETCH_ASSOC)){
        // print_r($row);
        $arr[]=$row;
     }
  }
  else{
    die("fali");
  }
  sleep(5);
  print_r( json_encode($arr));

?>

我本以为在js里面axios.all的两个请求都执行问之后才执行 console.log("all request finished");

但是结果不是,而是先输出了这句话,,,,,毁三观

 

4)axios({.....})的使用(比较简单,不具体说明了)
 getList(){
            const self=this;
            axios({
                method:get,
                url:../data/a2.php,
               // responseType:‘stream‘,
                params:{
                    id:2,
                }
            })
            .then(function(res) {
                    self.tea=res.data[0];
            });
        },

5)axios.create的使用,主要用于自定义请求配置。

详情看文档,,,,,

 

 

axios的简单使用

标签:logs   做了   简单   new   指正   method   charset   str   etl   

原文地址:http://www.cnblogs.com/evaling/p/7607603.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!