Vue09- vue-resource

使用 vue-resourceaxios 等第三方包实现 Ajax请求。

vue-resource 目前已不再更新,推荐使用 axios.

下面仅为介绍学习 vue-resource的笔记。

1、Get、Post、Jsonp 请求

<!-- 依赖:注意: Vue-resource 依赖于 Vue,注意导包先后顺序-->
<script src="lib/vue-2.4.0.js"></script>
<script src="lib/vue-resource-1.3.4.js"></script>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            list: []
        },
        methods: {
            // 发起get请求之后,通过 .then 来设置成功返回来的数据
            getInfo(){  // 发起get请求之后,通过 .then 来设置成功返回来的数据
                this.$http.get("http://www.liulongbin.top:3005/api/getprodlist")
                    .then(function (res) {
                        // 通过 result.body 拿到服务器返回的成功数据
                        console.log(res.body);
                        if (res.body.status === 0) {
                            this.list=res.body.message;
                            alert("成功:"+JSON.stringify(res));
                        } else {
                            alert("失败:" + JSON.stringify(res));
                        }
                    })
            },

            // 发起post请求
            postInfo(){  
                // 手动发起的 Post请求,默认没有表单格式,所以有的服务器处理不了
                // 通过Post方法的三个参数, { emulateJSON: true } 设置提交的内容为普通表单数据格式
                this.$http.post("http://jsonplaceholder.typicode.com/posts", {}, { emulateJSON: true }).then(result => {
                    console.log(result.body);
                })
            },
            
            // 发起JSONP 请求
            jsonpInfo(){  
                this.$http.jsonp("http://jsonplaceholder.typicode.com/users").then(result => {
                    console.log(result.body);
                })
            }
        }
    });
</script>
  • Get请求

    注意:发送请求,当发送get请求之后,通过 .then来设置成功的回调函数,通过res.body拿到服务器返回的成功的数据。当通过then指定回调函数之后,在回调函数中,可以拿到数据服务器返回res,先判断res.status是否等于0,如果等于0表示成功,可以把res.message赋值给this.list ();如果不等于0,提醒获取数据失败。

  • Post请求

    this.$http.post()中需要接受三个参数:

    • 第一个参数:要请求的url地址。
    • 第二个参数:要提交给服务器的数据,要以对象形式提交给服务器{name:this.name}。
    • 第三个参数:是一个配置对象,要以哪种表单数据类型提交过去。

2、JSONP请求

  • 由于浏览器的安全性限制,不允许AJAX访问 协议不同、域名不同、端口不同的数据接口,浏览器认为这种访问不安全。

  • 可以通过动态创建script标签的形式,把script标签的src属性指向数据接口的地址,因为script标签不存在的跨域限制,因为script标签不存在跨域限制,这种数据获取方式,称作JSONP。根据JSONP的实现原理可知,JSONP只支持Get请求。

  • 实现

    1、先在客户端定义一个回调方法,预定义对数据的操作;

    2、再把这个回调方法的名称,通过URL传参的形式,提交到服务器的数据接口。

    3、 服务器数据接口组织好要发送给客户端的数据,再拿着客户端传递过来的回调方法名称,拼接出一个调用这个方法的字符串,发送给客户端去解析执行。

    4、客户端拿到服务器返回的字符串之后,当作Script脚本去解析执行,这样就能够拿到JSONP的数据了。

<body>
<script>
    function showInfo123(data) {
        console.log(data)
    }
</script>
<!-- [jsonp原理] 跨域获取数据,并执行脚本 -->
<script src="http://127.0.0.1:3000/getscript?callback=showInfo123"></script>
  • node简易服务
// 启动这个服务:  nodemon ./app.js

// 导入 http 内置模块
const http = require('http');
// 这个核心模块,能够帮我们解析 URL地址,从而拿到  pathname  query
const urlModule = require('url');

// 创建一个 http 服务器
const server = http.createServer();
// 监听 http 服务器的 request 请求
server.on('request', function (req, res) {

    // const url = req.url
    const { pathname: url, query } = urlModule.parse(req.url, true);

    if (url === '/getscript') {
        // 拼接一个合法的JS脚本,这里拼接的是一个方法的调用
        // var scriptStr = 'show()'

        var data = {
            name: 'xiaowei,
            age: 18,
            gender: '女孩'
        };

        var scriptStr = `${query.callback}(${JSON.stringify(data)})`;
        // res.end 发送给 客户端, 客户端去把 这个 字符串,当作JS代码去解析执行
        res.end(scriptStr)
    } else {
        res.end('404')
    }
});

// 指定端口号并启动服务器监听
server.listen(3000, function () {
    console.log('server listen at http://127.0.0.1:3000')
});

3、v-reource案例

<!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="ie=edge">
    <title>Document</title>
    <script src="./lib/vue-2.4.0.js"></script>
    <script src="./lib/vue-resource-1.3.4.js"></script>
    <link rel="stylesheet" href="lib/bootstrap-3.3.7.css">
</head>

<body>
<div id="app">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">添加品牌</h3>
        </div>
        <div class="panel-body form-inline">
            <label>
                Name:
                <input type="text" v-model="name" class="form-control">
            </label>
            <input type="button" value="添加" @click="add" class="btn btn-primary">
        </div>
    </div>


    <table class="table table-bordered table-hover table-striped">
        <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Ctime</th>
            <th>Operation</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="item in list" :key="item.id">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.ctime}}</td>
            <td>
                <a href="" @click.prevent="del(item.id)">删除</a>
            </td>
        </tr>
        </tbody>
    </table>
</div>

<script>
    // 如果我们通过全局配置了,请求的数据接口 根域名,则 ,在每次单独发起 http 请求的时候,
    // 请求的 url 路径,应该以相对路径开头,前面不能带 /  ,否则 不会启用根路径做拼接;
    Vue.http.options.root = 'http://www.liulongbin.top:3005';
    // 全局启用 emulateJSON 选项
    Vue.http.options.emulateJSON = true;

    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
        el: '#app',
        data: {
            name: '',
            list: [ // 存放所有品牌列表的数组
            ]
        },
        created() { // 当 vm 实例 的 data 和 methods 初始化完毕后,vm实例会自动执行created 这个生命周期函数
            this.getAllList()
        },
        methods: {
            getAllList() { // 获取所有的品牌列表
                this.$http.get('api/getprodlist').then(result => {
                    // 注意: 通过 $http 获取到的数据,都在 result.body 中放着
                    var result = result.body
                    if (result.status === 0) {
                        // 成功了
                        this.list = result.message
                    } else {
                        // 失败了
                        alert('获取数据失败!')
                    }
                })
            },
            add() {  // 添加品牌列表到后台服务器
                this.$http.post('api/addproduct', { name: this.name }).then(result => {
                    if (result.body.status === 0) {
                        // 成功了!
                        // 添加完成后,只需要手动,再调用一下 getAllList 就能刷新品牌列表了
                        this.getAllList()
                        // 清空 name
                        this.name = ''
                    } else {
                        // 失败了
                        alert('添加失败!')
                    }
                })
            },
            del(id) { // 删除品牌
                this.$http.get('api/delproduct/' + id).then(result => {
                    if (result.body.status === 0) {
                        // 删除成功
                        this.getAllList()
                    } else {
                        alert('删除失败!')
                    }
                })
            }
        }
    });
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值