Vue是如何发送ajax?vue如何获取get、post请求?

1.1 axios

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中

axios的github:https://github.com/axios/axios

1.2 引入axios

可以用script引入

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

引入axios-0.18.0.js

在这里插入图片描述

1.3 案例

1.3.1 get请求

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
    .then(function (response) {
    console.log(response);
})
    .catch(function (error) {
    console.log(error);
});

// 可选地,上面的请求可以这样做
axios.get('/user', {
    params: {
        ID: 12345
    }
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});
 

1.3.2 post请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

为方便起见,为所有支持的请求方法提供了别名

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

1.4 代码:

【需求】:创建data/user.json文件

使用axios读取user.json文件的内容,并在页面上输出内容。

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>vuejs中axios数据调用</title>
    <script src="vue-2.5.17.js"></script>
    <script src="axios-0.18.0.js"></script>
</head>

<body>
<div id="app">
    {{message}}
</div>
</body>
<script>
    var vm = new Vue({
        el: "#app",
        data: {
            message: ''
        },
        methods: {
            init: function(){
                axios.get("./data/user.json").then(function(response){
                    // alert(response);
                    alert(JSON.stringify(response))
                    alert(response.data[0].username);
                })
            }
        },
        created: function(){
            this.init();
        }
    });
</script>

</html>

创建data目录,创建user.json

[
  {"username":"张三","age":22},
  {"username":"李四","age":21},
  {"username":"王五","age":20},
  {"username":"赵六","age":23}
]

在这里插入图片描述

  • 1
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值