1. 程式人生 > >vue.js的ajax和jsonp請求

vue.js的ajax和jsonp請求

引入vue.js
<script src="vue.js"></script>
引入vue外掛
<script src="vue-resource.js"></script>
html程式碼
<div id="v">
  <span>{{txt}}</span>
  <input type="text"  v-on:keyup.enter="init(55)" v-model="txt">
  <input type="button"  v-on:click="cli(55)">
</div>
js程式碼
<pre name="code" class="javascript">//全域性使用(已get請求為例)
Vue.http.get(url, [options]).then(successCallback, errorCallback);

//在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為例

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