vue-resource发起get、post、jsonp请求
目录
一、请求地址
二 、演示
三、总结
一、请求地址
vue-resource是和 vue 高度集成的第三方包,它可以便利发送数据的请求。除了 vue-resource 还可以使用 axios 的第三方包实现数据的请求。
常见的数据请求类型:get post jeonp
测试的URL请求资源地址:
Get请求地址:http://vue.studyit.i0/api/getlunbo
Post请求地址:http://vue.studyit.i0/api/post
Jsonp请求地址:http://vue.studyit.i0/api/jsonp
二、演示
1.Get请求
<input type=”button”value=”get请求”@click=”getinfo”>
//设置点击事件
<script src=”./lib/vue-resource-1.3.4ja”></script>
getInfo() {//发起 get 请求
this.$http.get('http://vue.studyit.io/api/getlunbo').then(function result)
console.log(result.body)//通过 result.body 拿到服务器返回的成功的数据。
在 vue 包后导入 vue-resoure, vue-resoure 依赖于 vue ,要注意先后顺序。
<script src=”./lib/vue-resource-1.3.4ja”></script>在 Vue
上挂载了 $http 属性,通过 $http 可以.出来一些方法。Get 中接
受的参数第一个是 url 地址,第二个是可选的参数。当发起 get
请求后,通过 then 来设置成功的回调函数,失败的回调可以不传,
成功的回调必须传。
举例:
this.$http.get(‘/someurl’,[options]).then(successCallback,errorCallback)
其中,在代码中出现.then,就代表这个方法是通过 promise 封装。
2.Post请求
postInfo() {//发起 post 请求
this.$http.post('http://vue.studyit.io/api/post',{},{ emulateJSON:true }).then(result →{
console.log(result.body)
发起 post 请求。 post的参数第一个是请求的地址,第二个是发送给服务器的数据对象,第三个是选项。举例:
this.$http.post(‘/someurl’,[body][options]).then(successCallback,errorCallback)
通过 then 成功的回调。当前的服务器只接受表单类型的提交,表单类型的提交格式是:application/x-www-form-urlencoded手动发起的 Post 请求,默认没有表单格式,一些服务器处理不了。所以需要做进一步的设计,
通过设置 post 方法的第三个参数,设置提交的内容类型为普通表单数据格式。在使用 post 方法时,第三个参数一般设置为emulateJSON:true。
Options类型
3.jsonp请求
jsonpInfo(){//发起 JSONP 请求
this.$http.jsonp('http://vue.studyit.io/api/isonp').then(result=>{
console.log(result.body)
jsonp的参数第一个是地址,第二个是配置对象。
三、总结
get和 jsonp 较为类似,直接赋予地址,通过.then拿到成功的回调设置即可。但是 post 较为复杂,第一个参数是 url 地址,第二个参数是提交给服务器的数据,第三个参数规定了表单格式,以普通表单进行数据提交。