React技術棧-react使用的Ajax請求庫實戰案例


         React技術棧-react使用的Ajax請求庫實戰案例

                                  作者:尹正傑

版權聲明:原創作品,謝絕轉載!否則將追究法律責任。

 

 

一.常見的Ajax請求庫

  溫馨提示:
    React本身只關注於界面, 並不包含發送ajax請求的代碼
    前端應用需要通過ajax請求與后台進行交互(json數據)
    react應用中需要集成第三方ajax庫(或自己封裝)

  常用的ajax請求庫
    jQuery: 
      比較重, 如果需要另外引入,生產環境中不建議使用。
    axios: 
      輕量級, 建議使用,axios有以下特點:
        1>.封裝XmlHttpRequest對象的ajax;
        2>.promise風格(then/catch);
        3>.可以用在瀏覽器端和node服務器端;
    fetch: 
      原生函數, 但老版本瀏覽器不支持
        1>.不再使用XmlHttpRequest對象提交ajax請求
        2>.為了兼容低版本的瀏覽器, 可以引入兼容庫fetch.js

 

二.使用axios案例

1>.HTML源代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用axios案例</title>
</head>
<body>
    <div id="box1"></div>

    <!--導入 React的核心庫-->
    <script type="text/javascript" src="../js/react.development.js"></script>
    <!--導入提供操作DOM的react擴展庫-->
    <script type="text/javascript" src="../js/react-dom.development.js"></script>
    <!--導入解析JSX語法代碼轉為純JS語法代碼的庫-->
    <script type="text/javascript" src="../js/babel.min.js"></script>
    <!--導入解析解析props屬性的庫-->
    <script type="text/javascript" src="../js/prop-types.js"></script>
    <!--導入axios庫-->
    <script type="text/javascript" src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>

    <script type="text/babel">
        //1>.定義組件
        class MostStarRepo extends React.Component{
            state = {
                response_name:'',
                response_url:''
            }

            //在初始化階段就異步發送請求。
            componentDidMount(){
                const url = `https://api.github.com/search/repositories?q=r&sort=stars`;
                //使用axios發送異步的Ajax請求
                axios.get(url)
                    .then(response => {
                        console.log(response);
                        const result = response.data;
                        //得到數據
                        const {name,html_url} = result.items[0];
                        //更新狀態
                        this.setState({response_name:name,response_url:html_url});
                    })
                    //異常處理
                    .catch((error) => {
                        console.log(error.message);
                    })

            }

            render(){
                const {response_name,response_url} = this.state;
                if(!response_name){
                    return <h1>Loading....</h1>
                }else{
                    return <h1>Most star repo is <a href={response_url}>{response_name}</a></h1>
                }
            }
        }

        //2>.渲染組件
        ReactDOM.render(<MostStarRepo />,document.getElementById("box1"));


    </script>
</body>
</html>
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Axios的GET請求
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});
Axios的POST請求

2>.瀏覽器打開以上代碼渲染結果

 

三.使用fetch案例

1>.HTML源代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用axios案例</title>
</head>
<body>
    <div id="box1"></div>

    <!--導入 React的核心庫-->
    <script type="text/javascript" src="../js/react.development.js"></script>
    <!--導入提供操作DOM的react擴展庫-->
    <script type="text/javascript" src="../js/react-dom.development.js"></script>
    <!--導入解析JSX語法代碼轉為純JS語法代碼的庫-->
    <script type="text/javascript" src="../js/babel.min.js"></script>
    <!--導入解析解析props屬性的庫-->
    <script type="text/javascript" src="../js/prop-types.js"></script>
    <!--導入axios庫-->
    <script type="text/javascript" src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>

    <script type="text/babel">
        //1>.定義組件
        class MostStarRepo extends React.Component{
            state = {
                response_name:'',
                response_url:''
            }

            //在初始化階段就異步發送請求。
            componentDidMount(){
                const url = `https://api.github.com/search/repositories?q=r&sort=stars`;
                //使用axios發送異步的Ajax請求
                // axios.get(url)
                //     .then(response => {
                //         console.log(response);
                //         const result = response.data;
                //         //得到數據
                //         const {name,html_url} = result.items[0];
                //         //更新狀態
                //         this.setState({response_name:name,response_url:html_url});
                //     })
                //     //異常處理
                //     .catch((error) => {
                //         console.log(error.message);
                //     })

                //使用fetch發送異步的Ajax請求
                fetch(url)
                    .then(response => {
                        return response.json()
                    })
                    .then(data => {
                        //得到數據
                        const {name,html_url} = data.items[0];
                        //更新狀態
                        this.setState({response_name:name,response_url:html_url});
                    })
                    //異常處理
                    .catch((error) => {
                        console.log(error.message);
                    })
            }

            render(){
                const {response_name,response_url} = this.state;
                if(!response_name){
                    return <h1>Loading....</h1>
                }else{
                    return <h1>Most star repo is <a href={response_url}>{response_name}</a></h1>
                }
            }
        }

        //2>.渲染組件
        ReactDOM.render(<MostStarRepo />,document.getElementById("box1"));


    </script>
</body>
</html>
fetch(url).then(function(response) {
  return response.json()
}).then(function(data) {
  console.log(data)
}).catch(function(e) {
  console.log(e)
});
Fetch的GET請求
fetch(url, {
  method: "POST",
  body: JSON.stringify(data),
}).then(function(data) {
  console.log(data)
}).catch(function(e) {
  console.log(e)
})
Fetch的POST請求

2>.瀏覽器打開以上代碼渲染結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM