Web/21-Vue基础/02-Vue中的Ajax请求.md
2018-04-20 23:44:34 +08:00

48 lines
1.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## vue-resource
官网链接:
- http相关<https://github.com/pagekit/vue-resource/blob/master/docs/http.md>
按照先后顺序导入vue.js和vue-resource.js文件。
### get 请求
```javascript
this.$http.get(url)
.then(function (response) {
var data = response.body; //response.body是要获取的数据
},
function (err) {
//err是异常数据
});
```
获取到的`response.body`就是要获取的数据,但直接打印出来是 object所以要记得转成string。
### jsonp
20180420_2250.png
```javascript
// 利用vue-resource中的jsonp方法实现跨域请求数据这里要注意的是
// url后面不需要跟callback=fn这个参数了jsonp方法会自动加上
this.$http.jsonp('http://vuecms.ittun.com/api/getlunbo?id=1')
.then(function (response) {
console.log(JSON.stringify(response.body));
}, function (err) {
//err是异常数据
});
```
请求结果:
20180420_2256.png