Vue-resourse 实现get,post,jsonp请求
Vue-resourse
CDN引用地址:https://cdn.jsdelivr.net/npm/vue-resource@1.5.1
代码展示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| <div id="app"> <input type="button" name="" value="get请求" @click="getInfo"> <input type="button" name="" value="post请求" @click="postInfo"> <input type="button" name="" value="jsonp请求" @click="jsonpInfo"> </div> <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script> <script type="text/javascript"> var vm = new Vue({ el:'#app', data:{
}, methods:{ getInfo:function () { this.$http.get('http://jsonplaceholder.typicode.com/users').then(result=>{ console.log(result.body) },result=>{ }) }, postInfo:function(){ this.$http.post('http://jsonplaceholder.typicode.com/users',{},{ emulateJSON : true }).then(result=>{ console.log(result.body) }) }, jsonpInfo:function(){ this.$http.jsonp('http://jsonplaceholder.typicode.com/users').then(function(result){ console.log(result.body) }) } }, }) </script>
|
演示:
点击演示
get
1
| this.http.get('/someUrl', [config]).then(successCallback, errorCallback);
|
post
1
| this.$http.post('/someUrl', [body], [config]).then(successCallback, errorCallback);
|
注意
发起post请求格式:application/x-wwww-form,-urlencodeed
手动发起的post请求,默认没有表单格式,有的服务器处理不了
这里需要添加config
属性 emulateHTTP
详见:https://github.com/pagekit/vue-resource/blob/develop/docs/http.md
jsonp
1
| jsonp('url', [config]).then(successCallback, errorCallback);
|