vue-resource实现ajax

vue-resource实现get、post、jsonp请求,综合代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./lib/vue.js"></script>
  <!-- 注意:vue-resource依赖于Vue ,所以先后顺序要注意 -->
  <script src="./lib/vue-resource-1.3.4.js"></script>
</head>
<body>
  <div id="app">
    <input type="button" value="get请求" @click="getInfo">
    <input type="button" value="post请求" @click="postInfo">
    <input type="button" value="jsonp请求" @click="jsonpInfo">
  </div>
  <script>
    var vm = new Vue({
      el: '#app',
      data: {},
      methods: {
        getInfo() { //发起get请求
          this.$http.get('https://douban.uieee.com/v2/movie/in_theaters').then(result=> {
            //通过 result.body 拿到服务器返回的成功的数据
             console.log(result.body)
          })
        },
        postInfo() { 
          //手动发起的Post请求,默认没有表单格式
          //通过post 方法的第三个参数 {emulateJSON:true},设置 提交的内容类型 为普通表单格式
          this.$http.post('https://douban.uieee.com/v2/movie/top250', {}, {
            emulateJSON: true
          }).then(result => {
            console.log(result.body)
          })
        },
        jsonpInfo() { //发起JSONP请求
          this.$http.jsonp('https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web', {
            params: {
              wd: 'Vue入门' //查找的关键字
            }
          }).then(
            result => {
              console.log(result.body)
            })
        }
      }
    })
  </script>
</body>
</html>

显示效果:

  • get请求

在这里插入图片描述

  • post请求
    在这里插入图片描述
  • jsonp请求
    在这里插入图片描述
发布了43 篇原创文章 · 获赞 1 · 访问量 3116

猜你喜欢

转载自blog.csdn.net/u011523953/article/details/105104980