除了 vue-resource 之外,还可以使用 `axios` 的第三方包实现实现数据的请求( `axios`不支持跨域请求)
引入vue-resource
<script src="js/vue.js"></script>
<script src="js/vue-resource.js"></script>
基本语法
引入vue-resource后,可以基于全局的Vue对象使用http,也可以基于某个Vue实例使用http。
// 基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
// 在一个Vue实例内使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
在发送请求后,使用then
方法来处理响应结果,then
方法有两个参数,第一个参数是响应成功时的回调函数,第二个参数是响应失败时的回调函数。
then
方法的回调函数也有两种写法,第一种是传统的函数写法,第二种是更为简洁的ES 6的Lambda写法:
// 传统写法
this.$http.get('/someUrl', [options]).then(function(response){
// 响应成功回调
}, function(response){
// 响应错误回调
});
// Lambda写法
this.$http.get('/someUrl', [options]).then((response) => {
// 响应成功回调
}, (response) => {
// 响应错误回调
});
1. 常见的数据请求类型? get post jsonp
2.JSONP的实现原理
+ 由于浏览器的安全性限制,不允许AJAX访问 协议不同、域名不同、端口号不同的 数据接口,浏览器认为这种访问不安全;
+ 可以通过动态创建script标签的形式,把script标签的src属性,指向数据接口的地址,因为script标签不存在跨域限制,这种数据获取方式,称作JSONP(注意:根据JSONP的实现原理,知晓,JSONP只支持Get请求);
+ 具体实现过程:
- 先在客户端定义一个回调方法,预定义对数据的操作;
- 再把这个回调方法的名称,通过URL传参的形式,提交到服务器的数据接口;
- 服务器数据接口组织好要发送给客户端的数据,再拿着客户端传递过来的回调方法名称,拼接出一个调用这个方法的字符串,发送给客户端去解析执行;
- 客户端拿到服务器返回的字符串之后,当作Script脚本去解析执行,这样就能够拿到JSONP的数据了;
+ 带大家通过 Node.js ,来手动实现一个JSONP的请求例子;
const http = require('http');
// 导入解析 URL 地址的核心模块
const urlModule = require('url');
const server = http.createServer();
// 监听 服务器的 request 请求事件,处理每个请求
server.on('request', (req, res) => {
const url = req.url;
// 解析客户端请求的URL地址
var info = urlModule.parse(url, true);
// 如果请求的 URL 地址是 /getjsonp ,则表示要获取JSONP类型的数据
if (info.pathname === '/getjsonp') {
// 获取客户端指定的回调函数的名称
var cbName = info.query.callback;
// 手动拼接要返回给客户端的数据对象
var data = {
name: 'zs',
age: 22,
gender: '男',
hobby: ['吃饭', '睡觉', '运动']
}
// 拼接出一个方法的调用,在调用这个方法的时候,把要发送给客户端的数据,序列化为字符串,作为参数传递给这个调用的方法:
var result = `${cbName}(${JSON.stringify(data)})`;
// 将拼接好的方法的调用,返回给客户端去解析执行
res.end(result);
} else {
res.end('404');
}
});
server.listen(3000, () => {
console.log('server running at http://127.0.0.1:3000');
});
3. vue-resource 的配置步骤:
+ 直接在页面中,通过`script`标签,引入 `vue-resource` 的脚本文件;
+ 注意:引用的先后顺序是:先引用 `Vue` 的脚本文件,再引用 `vue-resource` 的脚本文件;
4. 发送get请求:
getInfo() { // get 方式获取数据
this.$http.get('http://127.0.0.1:8899/api/getlunbo').then(res => {
console.log(res.body);
})
}
//带参数
this.$http.get('get.php',{params : {a:1,b:2}}).then(function(res){
document.write(res.body);
},function(res){
console.log(res.status);
});
5 发送post请求:
postInfo() {
var url = 'http://127.0.0.1:8899/api/post';
// post 方法接收三个参数:
// 参数1: 要请求的URL地址
// 参数2: 要发送的数据对象
// 参数3: 指定post提交的编码类型为 application/x-www-form-urlencoded
this.$http.post(url, { name: 'zs' }, { emulateJSON: true }).then(res => {
console.log(res.body);
});
}
6. 发送JSONP请求获取数据:
jsonpInfo() { // JSONP形式从服务器获取数据
var url = 'http://127.0.0.1:8899/api/jsonp';
this.$http.jsonp(url).then(res => {
console.log(res.body);
});
}
<script>
// 创建 Vue 实例,得到 ViewModel
var vm = new Vue({
el: '#app',
data: {},
methods: {
getInfo() { // 发起get请求
// 当发起get请求之后, 通过 .then 来设置成功的回调函数
this.$http.get('http://vue.studyit.io/api/getlunbo').then(function (result) {
// 通过 result.body 拿到服务器返回的成功的数据
// console.log(result.body)
})
},
postInfo() { // 发起 post 请求 application/x-wwww-form-urlencoded
// 手动发起的 Post 请求,默认没有表单格式,所以,有的服务器处理不了
// 通过 post 方法的第三个参数, { emulateJSON: true } 设置 提交的内容类型 为 普通表单数据格式
this.$http.post('http://vue.studyit.io/api/post', {}, { emulateJSON: true }).then(result => {
console.log(result.body)
})
},
jsonpInfo() { // 发起JSONP 请求
this.$http.jsonp('http://vue.studyit.io/api/jsonp').then(result => {
console.log(result.body)
})
}
}
});
</script>
使用 vue-resource 的 jsonp 处理跨域请求:demo
<div id="app">
请输入关键字:<input type="text" v-model="keyword" @keyup="sendJsonP(keyword)">
<ul>
<li v-for="r in result">{{r}}</li>
</ul>
</div>
<script>
window.onload = function () {
new Vue({
el: '#app',
data: {
keyword: '',
result: ''
},
methods: {
sendJsonP(keyword) {
let url = 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web';
this.$http.jsonp(url, {
params: {
wd: keyword
},
jsonp: 'cb'//jsonp默认是callback,百度缩写成了cb,所以需要指定下 }
}).then(res => {
if (res.data.g) {
this.result = res.data.g.map(x => x['q']);
} else {
this.result = [];
}
});
}
}
});
}
</script>
效果: