使用axios 发送 post 或者 get请求

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="i.e.=edge">
<title>Document</title>

<script src="../vue2.4.4.js"></script>
<script src="../axios.js"></script>
</head>
<body>
<div id="app">
    <button @click="getApiData">点击得到数据</button>
    <button @click="postApiData">点击提交数据</button>
    {{ name }}
</div>

<script>
    axis.defaults.baseURL = "http://157.122.54.189:9093/";//设置统一端口号
    Vue.prototype.$http = axios;

    new Vue({
        el:'#app',
        data:{
            name:""
        },
        methods: {
                getApiData:function(){
                    var url = "api/getprodlist";    
                    _this = this;
                    this.$http.get(url).then( function(result)  {
                            //then方法的回调函数 result 是返回的数据
                            _this.name = result.data.message[0].name;
                    } ).catch(function() {
                        alert("出错了");
                    });
                },

                postApiData:function() {
                        var url = "api/addproduct";    
                        //post 有两个参数 请求的路径  提交的参数  直接传入字符串 也可以对象的形式传入
                        this.$http.post(url, {name:"哈哈哈"}).then(function(res){
                             var resData = res.data;
                              if(resData.status == "0"){
                                   alert(resData.message); 
                               }else{
                                    alert("出错了");
                                }
                        }).catch(function(){
                                alert("出错了");
                        });
                }
        }
    })
</script>
posted @ 2018-03-15 15:32  haha瓜  阅读(423)  评论(0编辑  收藏  举报