ajax,cookie與hash 0719

ajax技術(shù)和php

1.get和post

1.1基本
  • 含義:可以通過form標(biāo)簽的method屬性指定發(fā)送請求的類型

  • 如果是get請求會將提交的數(shù)據(jù)拼接到URL后面,?userName=lnj&userPwd=123456

  • 如果是post請求會將提交的數(shù)據(jù)放到請求頭中

  • <form action="post.php" method="post">
      <input type="text" name="username"/><br />
      <input type="password" name="userpass" />
      <input type="submit" value="提交" />
    </form>
    
1.2 GET請求和POST請求的異同
  • 4.1相同點(diǎn):都是將數(shù)據(jù)提交到遠(yuǎn)程服務(wù)器
  • 不同點(diǎn):提交數(shù)據(jù)存儲的位置不同,GET請求會將數(shù)據(jù)放到URL后面,POST請求會將數(shù)據(jù)放到請求頭中
    • 提交數(shù)據(jù)大小限制不同:GET請求對數(shù)據(jù)有大小限制,POST請求對數(shù)據(jù)沒有大小限制
1.3 GET/POST請求應(yīng)用場景
  • GET請求用于提交非敏感數(shù)據(jù)和小數(shù)據(jù)
  • POST請求用于提交敏感數(shù)據(jù)和大數(shù)據(jù)

2.文件上傳

  • html代碼

  • <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>03-post-file</title>
    </head>
    <body>
    <!--
    注意:
    1.上傳文件一般使用POST提交
    2.上傳文件必須設(shè)置enctype="multipart/form-data"
    
    3.上傳的文件在PHP中可以通過$_FILES獲取
    4.PHP中文件默認(rèn)會上傳到一個臨時目錄, 接收完畢之后會自動刪除
    -->
    <!--
    默認(rèn)情況下服務(wù)器對上傳文件的大小是有限制的, 如果想修改上傳文件的限制可以修改xampp的php.ini文件
    file_uploads = On   ; 是否允許上傳文件 On/Off 默認(rèn)是On
    upload_max_filesize = 2048M       ; 上傳文件的最大限制
    post_max_size = 2048M             ; 通過Post提交的最多數(shù)據(jù)
    
    max_execution_time = 30000      ; 腳本最長的執(zhí)行時間 單位為秒
    max_input_time = 30000          ; 接收提交的數(shù)據(jù)的時間限制 單位為秒
    memory_limit = 2048M            ; 最大的內(nèi)存消耗
    -->
    <form action="03-post-file.php" method="post" enctype="multipart/form-data">
        <input type="file" name="upFile"><br>
        <input type="submit" value="上傳"><br>
    </form>
    </body>
    </html>
    
  • php代碼

  • <?php
    
    //print_r($_FILES);//會輸出一個關(guān)鍵字是表單中name的數(shù)組
    
    // 1.獲取上傳文件對應(yīng)的字典
    $fileInfo = $_FILES["upFile"];//包含當(dāng)前文件的名字,路徑,大小等信息
    //print_r($fileInfo);
    // 2.獲取上傳文件的名稱
    $fileName = $fileInfo["name"];
    // 3.獲取上傳文件保存的臨時路徑
    $filePath = $fileInfo["tmp_name"];
    
    // 4.移動文件
    move_uploaded_file($filePath, "./source/".$fileName);
    ?>
    

3.ajax

3.1 什么是ajax
  • AJAX 是與服務(wù)器交換數(shù)據(jù)并更新部分網(wǎng)頁的藝術(shù),在不重新加載整個頁面的情況下。
3.2 ajax用法:共五步
  • <script>
        window.onload = function (ev) {
            var oBtn = document.querySelector("button");
           oBtn.onclick = function (ev1) {
               // 1.創(chuàng)建一個異步對象
               var xmlhttp=new XMLHttpRequest();
               // 2.設(shè)置請求方式和請求地址
               /*
               method:請求的類型;GET 或 POST
               url:文件在服務(wù)器上的位置
               async:true(異步)或 false(同步)
               */
               xmlhttp.open("GET", "04-ajax-get.php", true);
               // 3.發(fā)送請求
               xmlhttp.send();
               // 4.監(jiān)聽狀態(tài)的變化
               xmlhttp.onreadystatechange = function (ev2) {
                   /*
                   0: 請求未初始化
                   1: 服務(wù)器連接已建立
                   2: 請求已接收
                   3: 請求處理中
                   4: 請求已完成,且響應(yīng)已就緒
                   */
                   //我們只需監(jiān)聽最后一個
                   if(xmlhttp.readyState === 4){
                       // 判斷是否請求成功 xmlhttp.status是狀態(tài)碼200~300或304
                       if(xmlhttp.status >= 200 && xmlhttp.status < 300 ||
                          xmlhttp.status === 304){
                           // 5.處理返回的結(jié)果
                           console.log("接收到服務(wù)器返回的數(shù)據(jù)");
                       }else{
                           console.log("沒有接收到服務(wù)器返回的數(shù)據(jù)");
                       }
     
                   }
               }
           }
       }
    </script>
    
3.3 在IE瀏覽器注意的問題
3.4 封裝get和post
  • JavaScript代碼

  • window.onload = function (ev) {
       var oBtn = document.querySelector("button");
       var res = encodeURIComponent("wd=張三");
       console.log(res);
       oBtn.onclick = function (ev1) {
           //  漢字不能識別需要轉(zhuǎn)換成這種格式 %E5%BC%A0%E4%B8%89
           // https://www.baidu.com/s?wd=%E5%BC%A0%E4%B8%89
           // url?key=value&key=value;
           //以下寫法的優(yōu)點(diǎn),參數(shù)的位置沒有影響,因?yàn)槭菍ο?        ajax({
                url:"04-ajax-get.php",
                data:{
                    "userName":"lnj",
                    "userPwd":"123456"
                },
                timeout: 3000,
                type:"post",
                success: function (xhr) {
                    alert(xhr.responseText);
                },
                error: function (xhr) {
                    alert("請求失敗");
                }
            });
       }
    }
    
    
  • 自己封裝的方法

  • function obj2str(data) {
        /*
        {
            "userName":"lnj",
            "userPwd":"123456",
            "t":"3712i9471329876498132"
        }
        */
        data = data || {}; // 如果沒有傳參, 為了添加隨機(jī)因子,必須自己創(chuàng)建一個對象
        data.t = new Date().getTime();
        var res = [];
        for(var key in data){
            // 在URL中是不可以出現(xiàn)中文的, 如果出現(xiàn)了中文需要轉(zhuǎn)碼
            // 可以調(diào)用encodeURIComponent方法
            // URL中只可以出現(xiàn)字母/數(shù)字/下劃線/ASCII碼
            res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key])); // [userName=lnj, userPwd=123456];
        }
        return res.join("&"); // userName=lnj&userPwd=123456
    }
    function ajax(option) {
        // 0.將對象轉(zhuǎn)換為所要格式字符串
        var str = obj2str(option.data); // key=value&key=value;
        // 1.創(chuàng)建一個異步對象,處理兼容性問題
        var xmlhttp, timer;
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        // 2.設(shè)置請求方式和請求地址
        /*
        method:請求的類型;GET 或 POST
        url:文件在服務(wù)器上的位置
        async:true(異步)或 false(同步)
        */
        if(option.type.toLowerCase() === "get"){
            xmlhttp.open(option.type, option.url+"?"+str, true);
            // 3.發(fā)送請求
            xmlhttp.send();
        }else{
            xmlhttp.open(option.type, option.url,true);
            // 注意點(diǎn): 以下代碼必須放到open和send之間
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send(str);
        }
    
        // 4.監(jiān)聽狀態(tài)的變化
        xmlhttp.onreadystatechange = function (ev2) {
            /*
            0: 請求未初始化
            1: 服務(wù)器連接已建立
            2: 請求已接收
            3: 請求處理中
            4: 請求已完成,且響應(yīng)已就緒
            */
            if(xmlhttp.readyState === 4){
                clearInterval(timer);
                // 判斷是否請求成功
                if(xmlhttp.status >= 200 && xmlhttp.status < 300 ||
                    xmlhttp.status === 304){
                    // 5.處理返回的結(jié)果
                    // console.log("接收到服務(wù)器返回的數(shù)據(jù)");
                    option.success(xmlhttp);
                }else{
                    // console.log("沒有接收到服務(wù)器返回的數(shù)據(jù)");
                    option.error(xmlhttp);
                }
            }
        }
        // 判斷外界是否傳入了超時時間
        if(option.timeout){
            timer = setInterval(function () {
                console.log("中斷請求");
                xmlhttp.abort();
                clearInterval(timer);
            }, option.timeout);
        }
    }
    
3.5 在jQuery中的ajax封裝
  • //jQuery已經(jīng)幫我們封裝好了ajax,直接用就行
     ajax({
        url:"04-ajax-get.php",
        data:{
            "userName":"lnj",
            "userPwd":"123456"
        },
        timeout: 3000,
        type:"post",
        success: function (xhr) {
            alert(xhr.responseText);
        },
        error: function (xhr) {
            alert("請求失敗");
        }
    });
    

4. cookie的使用

  • 4.1cookie基礎(chǔ)
    •     window.onload = function (ev) {
          /*
          cookie: 會話跟蹤技術(shù) 客戶端
          session:  會話跟蹤技術(shù)  服務(wù)端
      
          cookie作用:
          將網(wǎng)頁中的數(shù)據(jù)保存到瀏覽器中
      
          cookie生命周期:
          默認(rèn)情況下生命周期是一次會話(瀏覽器被關(guān)閉)
          如果通過expires=設(shè)置了過期時間, 并且過期時間沒有過期, 那么下次打開瀏覽器還是存在
          如果通過expires=設(shè)置了過期時間, 并且過期時間已經(jīng)過期了,那么會立即刪除保存的數(shù)據(jù)
      
          cookie注意點(diǎn):
          cookie默認(rèn)不會保存任何的數(shù)據(jù)
          cookie不能一次性保存多條數(shù)據(jù), 要想保存多條數(shù)據(jù),只能一條一條的設(shè)置
          cookie有大小和個數(shù)的限制
          個數(shù)限制: 20~50
          大小限制: 4KB左右
      
          cookie作用范圍:
          同一個瀏覽器的同一個路徑下訪問
          如果在同一個瀏覽器中, 默認(rèn)情況下下一級路徑就可以訪問
          如果在同一個瀏覽器中, 想讓上一級目錄也能訪問保存的cookie, 那么需要添加一個path屬性才可以;
          document.cookie = "name=zs;path=/;";
      
          例如:
          保存到了www.it666.com/jQuery/Ajax/路徑下,
          我們想在 www.it666.com/jQuery/Ajax/13-weibo/,
          和 www.it666.com/jQuery/ 路徑下也能訪問
      
          例如:
          我們在www.it666.com下面保存了一個cookie,
          那么我們在edu.it666.com中是無法訪問的
          如果想在edu.it666.com中也能訪問, 那么我們需要再添加一個domain屬性才可以;
          document.cookie = "name=zs;path=/;domain=it666.com;";
          */
          alert(document.cookie);
          var date = new Date();
          date.setDate(date.getDate() - 1);
          document.cookie = "age=33;expires="+date.toGMTString()+";";
          alert(document.cookie);
      
          document.cookie = "name=lnj;";
          document.cookie = "age=33;";
          alert(document.cookie);
          document.cookie = "name=lnj;age=33;gender=male;";
      
          document.cookie = "name=zs;path=/;domain=127.0.0.1;";
          }
      
      
  • 4.2 cookie的封裝
    • ;(function ($, window) {
          $.extend({
              addCookie: function (key, value, day, path, domain) {
                  // 1.處理默認(rèn)保存的路徑
                  var index = window.location.pathname.lastIndexOf("/")
                  var currentPath = window.location.pathname.slice(0, index);
                  path = path || currentPath;
                  // 2.處理默認(rèn)保存的domain
                  domain = domain || document.domain;
                  // 3.處理默認(rèn)的過期時間
                  if(!day){
                      document.cookie = key+"="+value+";path="+path+";domain="+domain+";";
                  }else{
                      var date = new Date();
                      date.setDate(date.getDate() + day);
                      document.cookie = key+"="+value+";expires="+date.toGMTString()+";path="+path+";domain="+domain+";";
                  }
              },
              getCookie:function (key) {
                  // console.log(document.cookie);
                  var res = document.cookie.split(";");
                  // console.log(res);
                  for(var i = 0; i < res.length; i++){
                      // console.log(res[i]);
                      var temp = res[i].split("=");
                      // console.log(temp);
                      if(temp[0].trim() === key){
                          return temp[1];
                      }
                  }
              },
              delCookie:function (key, path) {
                  addCookie(key, getCookie(key), -1, path);
              }
          });
      })(jQuery, window);
      
  • 5.hash

    • //hash 屬性是一個可讀可寫的字符串,該字符串是 URL 的錨部分(從 # 號開始的部分)。
      //假設(shè)設(shè)置了Location對象的 hash 屬性,那么瀏覽器就會轉(zhuǎn)移到當(dāng)前文檔中的一個指定的位置。
      //該屬性的作用與cookie類似
      //設(shè)置hash
       window.location.hash = 3;
      //獲取hash
       console.log(window.location.hash.substring(1));
      
      
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容