axios02-其他使用方式(推薦)

  • 推薦這種方式原因: 和以前的$.ajax()非常類似

    • 不同點: 使用promise技術處理異步操作結果

    • axios({
          url:'請求路徑',
          method:'請求方式',
          data:{ post請求參數 },
          params:{ get請求參數 }
      }).then(res=>{
          //成功回調
          //console.log(res)
      });
      
/*
1.學習目標介紹 : axios其他使用方式
2.學習路線 :
    (1)複習上一小節介紹的兩種方式
        axios.get().then()
        axios.post().then()
    (2)介紹第三種使用方式
        axios({
            url:'請求路徑',
            method:'請求方式',
            data:{ post請求參數 },
            params:{ get請求參數 }
        }).then(res=>{
            //成功回調
            //console.log(res)
        });
*/
<!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其他使用方式
        2.學習路線 :
            (1)複習上一小節介紹的兩種方式
                axios.get().then()
                axios.post().then()
            (2)介紹第三種使用方式
                axios({
                    url:'請求路徑',
                    method:'請求方式',
                    data:{ post請求參數 },
                    params:{ get請求參數 }
                }).then(res=>{
                    //成功回調
                    //console.log(res)
                });
        */

        //基本使用
        btn1.onclick = function () {
            axios({
                url: 'https://autumnfish.cn/api/joke',
                method: 'get',
            }).then(res => {
                console.log(res);
            })
        };

        //get請求
        btn2.onclick = function () {
            /* 
            細節: 如果get參數很少,可以使用ES6模板字符串直接在url拼接
            如果get參數很多,建議寫在params中
            */
            var num = 10;
            axios({
                url: `https://autumnfish.cn/api/joke/list?num=${num}`,
                method: 'get',
                // params:{
                //     num:10
                // }
            }).then(res => {
                console.log(res);
            })
        };

        //post請求
        btn3.onclick = function () {
            axios({
                url: 'http://ttapi.research.itcast.cn/mp/v1_0/authorizations',
                method: 'post',
                data: {
                    mobile: '18801185985',
                    code: '246810'
                }
            }).then(res => {
                console.log(res);
            })
        };
    </script>
</body>

</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章