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.')';



猜你喜欢

转载自blog.csdn.net/chenbalala/article/details/53032429