vue.js的ajax和jsonp請求


首先要聲明使用ajax 在 router下邊的 Index.js中

import VueResource from 'vue-resource';

Vue.use(VueResource);

ajax 和 jsonp 使用方法:

//在Vue實例類使用  
this.$http.get(url, [options]).then(successCallback, errorCallback);  
  
var test = new  Vue({  
  el:'#v',  
  data:{  
    jsonUrl:'xxxx',  
    jsonpUrl:'xxxxx',  
    req:{}  
    resData:[]  
  },  
  mthods:{  
    init:function(id){  
      this.$http.get(this.jsonUrl,this.req).then(function(res){  
        console.log(res);  
        this.$set('resData',res);  
      },function(res){  
        console.warn(res);  
      })  
    },  
    cli:function(id){  
      //jsonp請求  
      this.$http.jsonp(this.jsonpUrl).then(  
        function(res){  
          console.log(res);  
          this.$set('resData',res);  
        }  
      )  
    }  
  }  
})  

 

 

//需要注意的是jsonp請求的服務端返回的數據格式有些不一樣,下面以PHP為例 

[php] view plain copy
$call
= $_GET['callback']; $json = json_encode(['data'=>'tttttt']); echo $call.'('.$json.')';

 

 

vue請求數據方法

1、get 請求並傳遞參數方法

var param = {
                page: this.page,
                pageSize: this.pageSize,
                sort: 1
            };
            this.$http.get('/goods',{
                params: param
            }).then((response) => {
                response = response.body.result.list;
                this.shopList = response;
            });

2、原始的拼接參數方法

this.$http.get('/goods?page='+this.page+'&pageSize='+this.pageSize+'&sort=1').then((response) => {
                console.log(response)
                response = response.body.result.list;

                this.shopList = response;
                console.log(this.shopList)
            });

3、post的請求

 this.$http.post('in.php',{a:1,b:2},{emulateJSON:true}).then( (res) => {
                       console.log(res.data)
                 } )

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM