我的前端學習筆記23—— ajax

1,ajax 是什么?有什么作用?

  • ajax全稱為Asynchronous JavaScript and XML,可以實現在不重新加載整個頁面的情況下,對網頁的某一部分進行更新(異步)。
  • ajax在 瀏覽器與web服務器之間使用異步數據傳輸(HTTP請求)從服務器獲取數據。
    這里的異步指的是脫離當前瀏覽器頁面的請求、加載等單獨執行,這就意味著可以在不重新加載整個網頁的情況下,通過JavaScript發送請求,接受服務器傳來的數據,然后操作DOM將新數據對網頁的某部分進行更新,使用ajax最直觀的感受就是向服務器獲取新數據不需要刷新頁面等待了。

2,前后端開發聯調需要注意哪些事情?后端接口完成前如何 mock 數據?(npm install -g server-mock) 知識點視頻-如何 mock 數據

  • 前后端聯調是一種 真實業務數據本地mock數據之間來回切換以達到前后端分離架構下的不同開發速度時數據交換的一種方式方法。

  • 需要注意的事情有:

  • 約定前后端聯調的時間。

  • 約定雙方需要傳輸的數據和接口,在接口文檔中確定好參數的名稱、格式等。

  • 約定請求和響應的格式和內容。

  • 什么是mock數據:就是html發送一個ajax的請求。這個請求到哪里去,然后后端如何去響應這個請求。
    后端去獲取數據,并且定義接口;
    前端編寫頁面,并且和后端進行交互。

  • mock數據的方法有:

  • 使用server-mock或mock.js (http://mockjs.com/ )搭建模擬服務器,進行模擬測試(優點是不需要熟練掌握后臺PHP語言,采用熟悉的js語法);
    步驟:

  • 安裝node.js,呼出cmd命令

  • 選取一個文件夾,使用npm install -g server -mock進行全局安裝
    輸入mock start可以啟動一個web 服務器,他的根目錄就是你選取的文件夾,啟動完成之后,web服務器就可以展示了

  • 瀏覽器輸入localhost:8080就是你選取的文件夾

  • 使用mock init會自動的在文件夾下生成3個文件

  • 當html使用url對接口進行請求,會被router.js里相同的接口接受

  • 比如:

app.get("/loadMore",function(req,res){
//接受名為loadMore的php的參數
res.send({status:0,//向html發出正確的回參
          msg:"hello 饑人谷"http://回參中的值 
          })
})
  • 使用XAMPP等工具,編寫PHP文件來進行測試。

3,點擊按鈕,使用 ajax 獲取數據,如何在數據到來之前防止重復點擊?

方法一:使用button的disabled屬性,配合setTimeout 0,使在數據到來之前按鈕都不能被點擊

el.addEventListener("click",function(){ 
    this.disabled=true; ajax(); 
    setTimeout(this.disabled=false,0);
});

方法二:可設置標記變量flag,初始時設置flag為true.在用戶點擊提交按鈕后,判斷flag是否為true,如果是則發送ajax請求,并把flag設置為false。 等服務端給出響應后再把flag設置為true;

var ready = true;
    $('.add-more').on('click', function(){
    ... 
    if(!ready){
        return; 
    } 
    ready = false;
    $.ajax({
       ... 
       complete: function(){
            ready = true; 
            }
         }); 
    });
  • 代碼題:

一,封裝一個 ajax 函數,能通過如下方式調用

function ajax(opts){ 
    // todo ...
}
document.querySelector('#btn').addEventListener('click', function(){
    ajax({
        url: 'getData.php', //接口地址 
        type: 'get', // 類型, post 或者 get, 
        data: { 
            username: 'xiaoming', 
            password: 'abcd1234' 
        }, 
        success: function(ret){
        console.log(ret); // {status: 0} 
        }, 
       error: function(){
        console.log('出錯了') 
        } 
    })
});
  • 未封裝的普通ajax代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<!-- 需求是:在輸入框輸入用戶名,點擊按鈕,打包請求后發給后臺,后臺響應對應的姓名和年齡 -->
<input type="text" name="username" id="username" placeholder="請輸入用戶名">
<button class="btn">提交</button>
<dl id="ct">

</dl>

<script>
  document.querySelector('.btn').addEventListener('click',function(){
    var xmlhttp = new XMLHttpRequest();
    username = document.querySelector('#username').value;
    var url = 'renwu1.php' + '?username='+username;

    // GET方式:
    xmlhttp.open('GET',url,true);
    xmlhttp.send();
    //POST方式:
    // xmlhttp.open('POST','renwu1.php',true);
    // xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded");
    // xmlhttp.send("username="+username);

    xmlhttp.onreadystatechange = function(){
      if(xmlhttp.readyState==4 && xmlhttp.status==200){
        var userInfo = JSON.parse(xmlhttp.responseText);
        dealWith(userInfo);
      }
    }
  });
  function dealWith(userInfo){
    var str = '<dt>性別:</dt>';
    str += '<dd>'+ userInfo.sex +'</dd>';
    str += '<dt>年齡:</dt>';
    str += '<dd>'+userInfo.age +'</dd>';
    document.querySelector('#ct').innerHTML = str;
  }
</script>
</body>
</html>
  • PHP代碼:

    <?php
        // $username = $_GET['username'];
        $username = $_POST['username'];
        if($username === 'har'){
          $ret = array('sex'=>'男','age'=>'23');
        }else if($username === 'marry'){
          $ret = array('sex'=>'女','age'=>'22');
        }else{
          $ret = array('sex'=>'女','age'=>'27');
        }
        echo json_encode($ret);  //輸出標準json格式
    ?>
    
  • 封裝

function ajax(opts){
    var xmlhttp = new XMLHttpRequest();
    var dataStr = '';
    for(var key in opts.data){
      dataStr += key + '=' + opts.data[key]+'&'
    }
    dataStr = dataStr.substr(0,dataStr.length-1)

    if(opts.type.toLowerCase()==='post'){
      xmlhttp.open(opts.type,opts.url,true);
      xmlhttp.setRequestHeader('content-type','application/x-www-form-urlencoded');
      xmlhttp.send(dataStr);
    }
    if(opts.type.toLowerCase()==='get'){
      xmlhttp.open(opts.type,opts.url+'?'+ dataStr,true);
      xmlhttp.send();
    }

    xmlhttp.onreadystatechange = function(){
      if(xmlhttp.readyState == 4 && xmlhttp.status == 200 ){
        var json = JSON.parse(xmlhttp.responseText);
        opts.success(json);
      }
      if(xmlhttp.readyState == 4 && xmlhttp.status == 404 ){
        opts.error();
      }
    };
}

document.querySelector('#btn').addEventListener('click', function(){
    ajax({
        url: 'renwu1.php',   //接口地址
        type: 'get',               // 類型, post 或者 get,
        data: {
            username: document.querySelector('#username').value;
            password: document.querySelector('#password');
        },
        success: function(jsonData){
            dealWith(jsonData);       // {status: 0}
        },
        error: function(){
           console.log('出錯了')
        }
    })
});
function dealWith(userInfo){
  var str = '<dt>性別:</dt>';
  str += '<dd>'+ userInfo.sex +'</dd>';
  str += '<dt>年齡:</dt>';
  str += '<dd>'+userInfo.age +'</dd>';
  document.querySelector('#ct').innerHTML = str;
};

二,封裝一個 ajax 函數,能通過如下方式調用

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>任務二</title>
    <style media="screen">
      div,a{
        margin:0;
        padding:0;
      }
      .ct li{
        border:1px solid #ccc;
        height: 50px;
        line-height:50px;
        padding-left: 10px;
        margin: 10px 0;
        list-style:none;
      }
      .ct{
        padding-left: 0px;
      }
      .btn{
        border: 1px solid red;
        text-align: center;
        display: inline-block;
        height: 30px;
        width: 80px;
        line-height: 30px;
        cursor: pointer;
        position:absolute;
        left:50%;
        margin-top: 30px;
        margin-left: -40px;
        border-radius: 5px;
      }
      .btn:active{
        background-color: pink;
        color: #222;
      }
    </style>
  </head>
  <body>
    <ul class="ct">
      <li>內容1</li>
      <li>內容2</li>
    </ul>
    <a class="btn">加載更多</a>

    <script type="text/javascript">


      function ajax(opts){
        var xml = new XMLHttpRequest();
        var datastr = '';
        for(var key in opts.data){
          datastr += key + '=' + opts.data[key] + '&'
        }
        datastr=datastr.substr(0,datastr.length-1);

        if(opts.type.toLowerCase()=='get'){
          xml.open(opts.type,opts.url+'?'+datastr,true);
          xml.send();
        }
        if(opts.type.toLowerCase()=='post'){
          xml.open(opts.type,opts.url,true);
          xml.send(datastr);
          xml.setRequestHeader('content-type','application/x-www-form-urlencoded');
        }
        xml.onreadystatechange = function(){
          if(xml.readyState==4 && xml.status == 200){
            var json = JSON.parse(xml.responseText);
            opts.success(json);
          }
          if(xml.readyState==4 && xml.status ==404){
            opts.error();
          }
        }
      }

      var cur = 3;
      document.querySelector('.btn').addEventListener('click', function(){
          ajax({
              url: 'renwu2.php',   //接口地址
              type: 'get',               // 類型, post 或者 get,
              data: {
                start:cur,
                len: 6
              },
              success: function(json){
                  if(json.status==1){
                    append(json.data);
                    cur += 6;
                  }else{
                    console.log('失敗啦')
                  }     // {status: 0}
              },
              error: function(){
                 console.log('出錯了')
              }
          })
      });

      function append(arr){
        for(var i=0; i<arr.length; i++){
          var li = document.createElement('li');
          li.innerHTML = arr[i];
          document.querySelector('.ct').appendChild(li);
        }
      }
    </script>
  </body>
</html>

PHP端:

    <?php
        $start = $_GET['start'];
        $len = $_GET['len'];
        $items = array();

        for($i=0;$i<$len;$i++){
            array_push($items,'內容'.($start+$i));
        }
        $ret = array('status'=>1,'data'=>$items);
      sleep(1);
        echo json_encode($ret);

    ?>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,991評論 19 139
  • ajax 是什么?有什么作用? ajax是Asynchronous JavaScript + XML的簡寫。是一項...
    coolheadedY閱讀 200評論 0 0
  • 問答 1. ajax 是什么?有什么作用? Ajax是Asynchronous JavaScript and XM...
    Maggie_77閱讀 407評論 0 0
  • 信息:Pull Request 的命令行管理 思考:git am 命令可以將patch文件合入當前代碼;cherr...
    黑知更鳥閱讀 171評論 0 0
  • 凌波寒夢一聲起, 歲月驚雷, 獨嘆時光無限好, 一宵美夢。 滿含雙淚目歇歇, 春光依舊, 倚高獨盡天涯路, 志存高遠。
    鬼谷擺攤閱讀 159評論 2 5