vue前后端交互方式


1、大綱


2、前后端交互方式





3、Promise使用

異步
  • JavaScript的執行環境是「單線程」
  • 所謂單線程,是指JS引擎中負責解釋和執行JavaScript代碼的線程只有一個,也就是一次只能完成一項任務,這個任務執行完后才能執行下一個,它會「阻塞」其他任務。-* 這個任務可稱為主線程
  • 異步模式可以一起執行多個任務,但多次異步調用的順序不確定,不是按照我們寫代碼的順序得到結果
  • 如果異步調用結果存在依賴,代碼需要嵌套
JS中常見的異步調用
  • 定時任務
  • ajax
  • 事件函數


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div>前后端交互</div>
  <script type="text/javascript" src="js/jquery.js"></script>
  <script type="text/javascript">
    /*
      前后端交互-異步編程與Promise概述
    */
    // var ret = '---';
    // $.ajax({
    //   url: 'http://localhost:3000/data',
    //   success: function(data) {
    //     ret = data;
    //     console.log(ret)
    //   }
    // });
    // console.log(ret)

    // ----------------------------
    // $.ajax({
    //   url: 'http://localhost:3000/data',
    //   success: function(data) {
    //     console.log(data)
    //   }
    // });
    // $.ajax({
    //   url: 'http://localhost:3000/data1',
    //   success: function(data) {
    //     console.log(data)
    //   }
    // });
    // $.ajax({
    //   url: 'http://localhost:3000/data2',
    //   success: function(data) {
    //     console.log(data)
    //   }
    // });
    // -----------------------------------
    $.ajax({
      url: 'http://localhost:3000/data',
      success: function(data) {
        console.log(data)
        $.ajax({
          url: 'http://localhost:3000/data1',
          success: function(data) {
            console.log(data)
            $.ajax({
              url: 'http://localhost:3000/data2',
              success: function(data) {
                console.log(data)
              }
            });
          }
        });
      }
    });
    
    
    
  </script>
</body>
</html>



<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    /*
      Promise基本使用
    */
    // console.log(typeof Promise)
    // console.dir(Promise);

    var p = new Promise(function(resolve, reject){
      // 這里用於實現異步任務
      setTimeout(function(){
        var flag = false;
        if(flag) {
          // 正常情況
          resolve('hello');
        }else{
          // 異常情況
          reject('出錯了');
        }
      }, 100);
    });
    p.then(function(data){
      console.log(data)
    },function(info){
      console.log(info)
    });
  </script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    /*
      基於Promise發送Ajax請求
    */
    function queryData(url) {
      var p = new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
          if(xhr.readyState != 4) return;
          if(xhr.readyState == 4 && xhr.status == 200) {
            // 處理正常的情況
            resolve(xhr.responseText);
          }else{
            // 處理異常情況
            reject('服務器錯誤');
          }
        };
        xhr.open('get', url);
        xhr.send(null);
      });
      return p;
    }
    // queryData('http://localhost:3000/data')
    //   .then(function(data){
    //     console.log(data);
    //   },function(info){
    //     console.log(info)
    //   });
    // ============================
    // 發送多個ajax請求並且保證順序
    queryData('http://localhost:3000/data')
      .then(function(data){
        console.log(data)
        return queryData('http://localhost:3000/data1');
      })
      .then(function(data){
        console.log(data);
        return queryData('http://localhost:3000/data2');
      })
      .then(function(data){
        console.log(data)
      });
  </script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    /*
      then參數中的函數返回值
    */
    function queryData(url) {
      return new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
          if(xhr.readyState != 4) return;
          if(xhr.readyState == 4 && xhr.status == 200) {
            // 處理正常的情況
            resolve(xhr.responseText);
          }else{
            // 處理異常情況
            reject('服務器錯誤');
          }
        };
        xhr.open('get', url);
        xhr.send(null);
      });
    }
    queryData('http://localhost:3000/data')
      .then(function(data){
        return queryData('http://localhost:3000/data1');
      })
      .then(function(data){
        return new Promise(function(resolve, reject){
          setTimeout(function(){
            resolve(123);
          },1000)
        });
      })
      .then(function(data){
        return 'hello';
      })
      .then(function(data){
        console.log(data)
      })

  </script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    /*
      Promise常用API-實例方法
    */
    // console.dir(Promise);
    function foo() {
      return new Promise(function(resolve, reject){
        setTimeout(function(){
          // resolve(123);
          reject('error');
        }, 100);
      })
    }
    // foo()
    //   .then(function(data){
    //     console.log(data)
    //   })
    //   .catch(function(data){
    //     console.log(data)
    //   })
    //   .finally(function(){
    //     console.log('finished')
    //   });

    // --------------------------
    // 兩種寫法是等效的
    foo()
      .then(function(data){
        console.log(data)
      },function(data){
        console.log(data)
      })
      .finally(function(){
        console.log('finished')
      });
  </script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    /*
      Promise常用API-對象方法
    */
    // console.dir(Promise)
    function queryData(url) {
      return new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
          if(xhr.readyState != 4) return;
          if(xhr.readyState == 4 && xhr.status == 200) {
            // 處理正常的情況
            resolve(xhr.responseText);
          }else{
            // 處理異常情況
            reject('服務器錯誤');
          }
        };
        xhr.open('get', url);
        xhr.send(null);
      });
    }

    var p1 = queryData('http://localhost:3000/a1');
    var p2 = queryData('http://localhost:3000/a2');
    var p3 = queryData('http://localhost:3000/a3');
    // Promise.all([p1,p2,p3]).then(function(result){
    //   console.log(result)
    // })
    Promise.race([p1,p2,p3]).then(function(result){
      console.log(result)
    })
  </script>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    /*
      Fetch API 基本用法
    */
    fetch('http://localhost:3000/fdata').then(function(data){
      // text()方法屬於fetchAPI的一部分,它返回一個Promise實例對象,用於獲取后台返回的數據
      return data.text();
    }).then(function(data){
      console.log(data);
    })
  </script>
</body>
</html>






<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <script type="text/javascript">
    /*
      Fetch API 調用接口傳遞參數
    */

    // GET參數傳遞-傳統URL
    // fetch('http://localhost:3000/books?id=123', {
    //   method: 'get'
    // })
    //   .then(function(data){
    //     return data.text();
    //   }).then(function(data){
    //     console.log(data)
    //   });

    // GET參數傳遞-restful形式的URL
    // fetch('http://localhost:3000/books/456', {
    //   method: 'get'
    // })
    //   .then(function(data){
    //     return data.text();
    //   }).then(function(data){
    //     console.log(data)
    //   });

    // DELETE請求方式參數傳遞
    // fetch('http://localhost:3000/books/789', {
    //   method: 'delete'
    // })
    //   .then(function(data){
    //     return data.text();
    //   }).then(function(data){
    //     console.log(data)
    //   });

    // POST請求傳參
    // fetch('http://localhost:3000/books', {
    //   method: 'post',
    //   body: 'uname=lisi&pwd=123',
    //   headers: {
    //     'Content-Type': 'application/x-www-form-urlencoded'
    //   }
    // })
    //   .then(function(data){
    //     return data.text();
    //   }).then(function(data){
    //     console.log(data)
    //   });

    // POST請求傳參
    // fetch('http://localhost:3000/books', {
    //   method: 'post',
    //   body: JSON.stringify({
    //     uname: '張三',
    //     pwd: '456'
    //   }),
    //   headers: {
    //     'Content-Type': 'application/json'
    //   }
    // })
    //   .then(function(data){
    //     return data.text();
    //   }).then(function(data){
    //     console.log(data)
    //   });

    // PUT請求傳參
    fetch('http://localhost:3000/books/123', {
      method: 'put',
      body: JSON.stringify({
        uname: '張三',
        pwd: '789'
      }),
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then(function(data){
        return data.text();
      }).then(function(data){
        console.log(data)
      });
  </script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    /*
      Fetch響應結果的數據格式
    */
    fetch('http://localhost:3000/json').then(function(data){
      // return data.json();
      return data.text();
    }).then(function(data){
      // console.log(data.uname)
      // console.log(typeof data)
      var obj = JSON.parse(data);
      console.log(obj.uname,obj.age,obj.gender)
    })
  </script>
</body>
</html>


免責聲明!

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



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