- axios官網文檔:http://www.axios-js.com/
jQuery與axios對比 | jQuery | axios |
---|---|---|
1.ajax技術底層原理 | XMLHTTPRequest | XMLHTTPRequest |
2.體積大小 | 大 (包含大量dom操作與ajax) |
小 (只有ajax請求) |
3.是否支持ES6的Promise | 不支持(底層使用其他方案模擬實現) | 支持基於原生Promise封裝 |
4.兼容性 | 好 (兼容性是jQuery的強項) | 一般 (使用了新技術) |
1.1-axios基本使用
/*
1.學習目標介紹 : axios學習
(1) 瞭解axios作用 : 發送ajax請求
(2) axios發送get請求
(3) axios發送post請求
2.學習路線
(1)axios特點 (與jQuery區別)
* axios優點
a.體積小,只有發送ajax功能 (jQuery體積大,有一堆的DOM操作方法在vue中用不上)
b.技術先進:基於Promise技術封裝ajax
* axios缺點
a.瀏覽器兼容性不好(技術太先進了)
(2)axios基本使用
axios.get().then().catch().then();
axios.post().then().catch().then();
a. get()裏面寫url和參數
b. 第一個then() 表示成功回調 ,相當於jq裏面的success
c. catch() 表示失敗回調
d. 第二個then() 表示完成回調:無論成功失敗都會執行
(3)axios發送get請求傳參
(4)axios發送post請求傳參
*/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="btn1">基本使用</button>
<button id="btn2">點我發送get請求</button>
<button id="btn3">點我發送post請求</button>
<!-- 導入axios -->
<script src="./axios.js"></script>
<script>
/*
1.學習目標介紹 : axios學習
(1) 瞭解axios作用 : 發送ajax請求
(2) axios發送get請求
(3) axios發送post請求
2.學習路線
(1)axios特點 (與jQuery區別)
* axios優點
a.體積小,只有發送ajax功能 (jQuery體積大,有一堆的DOM操作方法在vue中用不上)
b.技術先進:基於Promise技術封裝ajax
* axios缺點
a.瀏覽器兼容性不好(技術太先進了)
(2)axios基本使用
axios.get().then().catch().then();
axios.post().then().catch().then();
a. get()裏面寫url和參數
b. 第一個then() 表示成功回調 ,相當於jq裏面的success
c. catch() 表示失敗回調
d. 第二個then() 表示完成回調:無論成功失敗都會執行
(3)axios發送get請求傳參
(4)axios發送post請求傳參
*/
//基本使用
btn1.onclick = function () {
/*
get() : 寫url和請求參數
then(res=>{}) : 成功回調, 相當於以前jq的success
catch(err=>{}):失敗回調, 一般可以省略不寫
then(()=>{}):完成回調, 表示請求完成,無論成功失敗都會執行。一般可以省略不寫
*/
axios.get('https://autumnfish.cn/api/joke').then(res => {
//請求成功
console.log(res);
}).catch(err => {
//請求失敗
console.log(err);
}).then(() => {
//請求完成
console.log('本次請求完成');
});
};
//get請求
btn2.onclick = function () {
//get方法第一個參數是url
//get方法第二個參數是對象類型 { params:{get參數對象} }
axios.get('https://autumnfish.cn/api/joke/list', {
params: {
num: 10
}
}).then(res => {
//請求成功
console.log(res);
});
};
//post請求
btn3.onclick = function () {
//post方法第一個參數是url
//post方法第二個參數是對象類型 { post參數對象 }
axios.post('http://ttapi.research.itcast.cn/mp/v1_0/authorizations', {
mobile: '18801185985',
code: '246810'
}).then(res => {
//請求成功
console.log(res);
});
};
</script>
</body>
</html>