WEB前端第六十一課——xhr對象POST請求、xhr兼容性、timeout、progress


1.xhr對象發送post請求

  Ajax中post請求與get請求不同之處在於多了一個表單,而get請求則是通過url發送附加信息。

  在xhr對象中,post請求可以通過FormData構建表單數據。

  語法:var formData = new FormData();

     formData.append('key',value);  //value為字符串時需要使用引號。

     xhr.send(formData);

  說明:formData的創建必須在“xhr.send(formData)”之前!

  示例:

    var userName = document.querySelector('.userName').value;

    var userCode = document.querySelector('.userCode').value;

    var formData = new FormData();  //FormData()為系統內置對象類

    formData.append('uName',userName);

    formData.append('uCode',userCode);

    xhr.send(formData);

  補充:

   ⑴ GET請求的主要特點:

    GET請求可被緩存,請求保留在瀏覽器歷史記錄中

    GET請求可被收藏為書簽

    GET請求不應在處理敏感數據時使用

    GET請求有長度限制

    GET請求只應當用於取回數據

   ⑵ POST請求的主要特點:

    POST請求不會被緩存,不會保留在瀏覽器歷史記錄中

    POST請求不能被收藏為書簽

    POST請求對數據長度沒有要求

   ⑶ 與POST相比,GET 更簡單也更快,並且在大部分情況下都能用。

    然而,在以下情況中,需使用POST請求:

      無法使用緩存文件(更新服務器上的文件或數據庫)

      向服務器發送大量數據(POST沒有數據量限制)

      發送包含未知字符的用戶輸入時,POST比GET更穩定也更可靠

    參考資料:w3cschool

2.xhr對象兼容問題

  xhr對象的獲取方式在 IE 和 非IE 環境下需要使用不同的方法。

  語法:

    IE瀏覽器支持的方法:ActiveXObject('')

    非IE環境支持的方法:XMLHttpRequest()

  因此,在創建 xhr 對象時需要進行判斷,示例如下:

    if(window.XMLHttpRequest){

      var xhr = new XMLHttpRequest();

    }else if(window.ActiveObject){

      var xhr = new ActiveXObject('');

    }

  也可以直接使用三目運算進行處理:

    xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("");

3.請求超時

  timeout 屬性值等於一個整數,用於設置當請求發出后等待接收響應的時間。

  ontimeout() 方法則是等待超時后,自動執行的回調函數。

  語法:

    xhr.timeout == n;    //時間單位“毫秒”,表示請求發出后響應等待時間。

    xhr.ontimeout = function(){

      console.log('The request for'+url地址+'time out');

    }

  說明:如果在設置的時間內沒能收到后台響應內容,則視為請求超時自動執行ontimeout函數。

     如果該屬性設置等於 0(默認值),表示沒有時間限制!

  代碼示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>原生Ajax請求</title>
<!--    <script src="../JScodeFile/jquery-1.8.3.js"></script>-->
</head>
<body>
    <label for="userName">登錄賬戶</label>
    <input type="text" id="userName" class="userName">
    <br>
    <label for="userCode">登錄密碼</label>
    <input type="text" id="userCode" class="userCode">
    <br>
    <button>登錄</button>
<script>
    var uName = document.querySelector('.userName');
    var uCode = document.querySelector('.userCode');
    var btn = document.querySelector('button');
    btn.onclick=function () {
//      var xhr=new XMLHttpRequest();   //創建對象,准備發送Ajax請求

//      考慮瀏覽器兼容性問題,創建 xhr 對象時需要進行判斷。
        if(window.XMLHttpRequest){
            var xhr = new XMLHttpRequest();
        }else{
            var xhr = new ActiveXObject();
        }
        xhr.onreadystatechange=function () {    //監聽后台接收請求狀態的變化
            if (xhr.readyState==4){             //判斷當前請求進行到何種狀態,屬性值 4 表示后台已經接收到前台請求
                if (xhr.status==200){           //判斷前台是否准確接收到后台反饋的數據,屬性值 200 表示通信成功
                    console.log(xhr.responseText);  //獲取后台反饋的完整數據,json串
                    console.log(typeof xhr.responseText);   //返回結果為 string 類型
                    console.log(JSON.parse(xhr.responseText));   //解析返回結果轉換為對象
                }
            }
        }
        xhr.timeout=2000;       //超時設置單位“毫秒”!!
        xhr.ontimeout=function(){
            alert('訪問超時,請刷新頁面重新加載。')
        }
//      使用 get 方式發送請求:
        xhr.open('get',"xhr.php?name="+uName.value+"&code="+uCode.value,true);
//         xhr.open('get',"xhr.php?name="+$('.userName').val()+"&code="+$('.userCode').val(),true);
        xhr.send(null);

//      使用 post 方式發送請求:
/*        xhr.open('post','xhr.php',true);
        var formD = new FormData();
        formD.append('name',uName.value);
        formD.append('code',uCode.value);
        xhr.send(formD);*/
    }
</script>
</body>
</html>
<?php
/*    $name1=$_POST['name'];
    $code1=$_POST['code'];*/
    $name1=$_GET['name'];
    $code1=$_GET['code'];
    $res = array('msg'=>'ok','info'=>$_GET);
    $res['userName']=$name1;
    $res['userCode']=$code1;
//    sleep(3);       //設置服務器睡眠,單位“秒”!!
    echo json_encode($res);
?>

4.進度條

  ⑴ progress

    HTML中使用<progress>標簽用於定義運行中的任務進度。

    progress屬性有:

      max,設置任務完成的值;

      value,設置任務當前進度值。

    注意:<progress>需要與JS配合使用顯示任務進度;

      <progress>不能用於表示度量衡,如存儲空間使用情況(使用<meter>標簽)

  ⑵ progress常用屬性

    lengthComputable,返回一個布爾值,表示當前進度是否有可計算長度,

             默認為true,表示進度沒有100%,進度100%時變為false;

    total,返回一個整數,表示當前進度的總長度,

      如果是通過HTTP下載資源,表示內容本身長度,不包含HTTP頭部的長度,

      如果lengthComputable屬性值為false,則total屬性無法取得正確的值。

    loaded,返回一個數值,表示當前進度已經完成的數量,

      該屬性值除以total屬性值,可以得到目前進度的百分比。

  ⑶ upload

    upload是XMLHttpRequest對象的一個屬性,其屬性值亦是一個對象,

      該對象定義了addEventListener()方法和整個progress事件集合。

  代碼示例:

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>進度條</title>
</head>
<body>
    <progress max="1" value="0"></progress>
    <input type="file" name="tempFile" class="tempFile" multiple><br>
    <button onclick="fileSubmit()">上傳文件</button>
    <script>
        function fileSubmit() {
            var files=document.querySelector('.tempFile').files;
        //  發送文件需要使用POST方式,創建FormData對象。
            var fileData=new FormData();
            for (var i=0,file;file = files[i];i++){
        //  將文件添加到FormData對象中。
                fileData.append('fileName',file.name);
            }
        //  使用append方法添加到FormData的數據,並不是以對象屬性的方式存儲,外界無法直接訪問到數據
        //  需要使用 for of 方法才能在控制台中打印輸出。
            for (var value of fileData.values()){
                console.log(value);
                console.log(typeof value);
            }
        //  Ajax請求對象
        //     var xhr=new XMLHttpRequest();    //直接創建
            if (window.XMLHttpRequest){         //兼容性方式創建
                var xhr=new XMLHttpRequest();
            }else if(window.ActiveXObject){
                var xhr=new ActiveXObject('');
            }
            // var xhr=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('');
        //  監聽請求響應通信狀態
            xhr.onreadystatechange=function () {
                if (xhr.readyState==4){
                    if (xhr.status==200){
                        console.log(JSON.parse(xhr.responseText));      //FormData添加文件時,無法直接解析輸出!
                    }
                }
            }
        //  任務進度監聽,當上傳進度發生改變時,回調函數自動執行
            var progressBar = document.querySelector('progress');
            xhr.upload.onprogress=function(eve){
                if (eve.lengthComputable){
                    progressBar.value = (eve.loaded/eve.total);
                }
            }
        //  准備發送請求上傳文件
            xhr.open('post','progress.php',true);
            xhr.send(fileData);
        }
    </script>
</body>
</html>
<?php
    echo json_encode($_POST['fileName']);
?>

 


免責聲明!

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



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