欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Vue-resource实现ajax请求和跨域请求示例

程序员文章站 2023-11-09 22:13:04
vue-resource是vue提供的体格http请求插件,如同jquery里的$.ajax,用来和后端交互数据的。 在使用时,首先需要安装vue-resource插...

vue-resource是vue提供的体格http请求插件,如同jquery里的$.ajax,用来和后端交互数据的。

在使用时,首先需要安装vue-resource插件

1.在项目跟目录上安装:

npm install vue-resource 

 2.引入resource插件

import vueresource from 'vue-resource'; 
vue.use(vueresource) 

3.发送请求:

this.$http.get("http://www.vrserver.applinzi.com/aixianfeng/apihome.php").then(function(res){ 
  console.log(res) 
 }) 

es6写法:

this.$http.get('url', [options]).then((res) => { 
// 处理成功的结果}, (res) => { // 处理失败的结果}); 

在发送请求后,使用then方法来处理响应结果,then方法有两个参数,第一个参数是响应成功时的回调函数,第二个参数是响应失败时的回调函数。

then方法的回调函数也有两种写法,第一种是传统的函数写法,第二种是更为简洁的es 6的lambda写法:

post请求:

this.$http.post("http://www.vrserver.applinzi.com/aixianfeng/apihome.php",{name:"abc"},{emulatejson:true}).then( 
   function (res) { 
    // 处理成功的结果 
    alert(res.body); 
   },function (res) { 
   // 处理失败的结果 
   } 
  );

jsonp请求:

new vue({ ready() { 
 this.$http.jsonp('/url', {name:"abc"}) .then(function (res){ 
  console.log(res) 
 }, function (res) { 
  console.log(res) 
  }); 
 } 
})

吐槽一下,现在应该没有用到json的了吧,有的话真呵呵呵了。

支持的http方法

vue-resource的请求api是按照rest风格设计的,它提供了7种请求api:

  • get(url, [options])
  • head(url, [options])
  • delete(url, [options])
  • jsonp(url, [options])
  • post(url, [body], [options])
  • put(url, [body], [options])
  • patch(url, [body], [options])

除了jsonp以外,另外6种的api名称是标准的http方法。当服务端使用rest api时,客户端的编码风格和服务端的编码风格近乎一致,这可以减少前端和后端开发人员的沟通成本。

客户端请求方法 服务端处理方法
this.$http.get(...) getxxx
this.$http.post(...) postxxx
this.$http.put(...) putxxx
this.$http.delete(...) deletexxx

options对象

发送请求时的options选项对象包含以下属性:

参数 类型 描述
url string 请求的url
method string 请求的http方法,例如:'get', 'post'或其他http方法
body object, formdatastring request body
params object 请求的url参数对象
headers object request header
timeout number 单位为毫秒的请求超时时间 (0 表示无超时时间)
before function(request) 请求发送前的处理函数,类似于jquery的beforesend函数
progress function(event) progressevent回调处理函数
credientials boolean 表示跨域请求时是否需要使用凭证
emulatehttp boolean 发送put, patch, delete请求时以http post的方式发送,并设置请求头的x-http-method-override
emulatejson boolean 将request body以application/x-www-form-urlencoded content type发送

emulatehttp的作用

如果web服务器无法处理put, patch和delete这种rest风格的请求,你可以启用enulatehttp现象。启用该选项后,请求会以普通的post方法发出,并且http头信息的x-http-method-override属性会设置为实际的http方法。

vue.http.options.emulatehttp = true;

emulatejson的作用

如果web服务器无法处理编码为application/json的请求,你可以启用emulatejson选项。启用该选项后,请求会以application/x-www-form-urlencoded作为mime type,就像普通的html表单一样。

vue.http.options.emulatejson = true;

response对象

response对象包含以下属性:

方法 类型 描述
text() string 以string形式返回response body
json() object 以json对象形式返回response body
blob() blob 以二进制形式返回response body
属性 类型 描述
ok boolean 响应的http状态码在200~299之间时,该属性为true
status number 响应的http状态码
statustext string 响应的状态文本
headers object 响应头

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。