除了 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>
效果: