Vue2.0学习笔记-13、vue-resouces(get、post以及jsonp跨域请求)

本文介绍了如何在Vue.js中使用vue-resource库进行get、post请求及jsonp跨域请求。通过示例代码展示了如何设置全局根路径、发起请求以及处理响应。在实际操作中,作者自己搭建了Express接口来配合请求。文章强调了学习新技术的同时掌握相关知识的重要性。
摘要由CSDN通过智能技术生成

1、get和post请求
代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!---引入vue-resouces资源,必须在引入vue以后再引入--->
    <script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
  </head>
  <body>
    <div id="app">
      {{msg}}

      <button @click="getJson">get请求</button>
      <button @click="postJson">post请求</button>
    </div>
    <script type="text/javascript">
      Vue.http.options.root = "http://localhost:3000/"; //设置全局根路径
      var vm = new Vue({
        el: "#app",
        data: {
          msg: null,
        },
        methods: {
          getJson: function () {
            this.$http.get("get").then(
              function (response) {
                this.msg = response.body;
              },
              function (error) {
                this.msg = error;
              }
            );
          },

          postJson: function () {
            this.$http.post("post/本田/245", { emulateJSON: true }).then(
              function (response) {
                this.msg = response.body;
              },
              function (error) {
                this.msg = error;
              }
            );
          },
        },
      });
    </script>
  </body>
</html>

get请求执行效果:
在这里插入图片描述
post请求执行效果:
在这里插入图片描述
上图中是post请求执行成功后返回的内容
3、jsonp跨域请求
代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
  </head>
  <body>
    <div id="app">{{msg}}</div>
    <script type="text/javascript">
      Vue.http.options.root = "http://localhost:3000/"; //设置全局根路径
      var vm = new Vue({
        el: "#app",
        data: {
          msg: null,
        },
        methods: {},
        mounted: function () {
          this.$http
            .jsonp("jsonp", {
              jsonp: "cb",//由于我在服务端将回调函数名称改为了cb,因此这里必须指明回调函数名称(服务端默认的回调函数名称为callback,vue-resouces的jsonp请求默认的回调函数名称也是callback)
            })
            .then(function (response) {
              if (response.status == 200) this.msg = response.body;
            });
        },
      });
    </script>
  </body>
</html>

这就是vue里面的ajax,没啥说的,自己敲两遍就懂了;麻烦的地方是:我照着网上的教程学这个地方,人家发送get、post和jsonp请求都有请求地址(Url),我也没有,我只能自己写,以前会写php和jsp,但是这两个技术都被淘汰了(主要是忘了,2333),没办法新学了express框架自己写的接口。多好,学一个新知识的同时又掌握了另一个新知识, 开心

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值