Ajax——12——jQuery封裝

一:使用jQuery裏的Ajax方法發送一個請求到遠程服務器

將jQuery框架包導入
重要代碼塊:

$.ajax({
                    type:"GET",
                    url:"a.php",
                    data:"userName=lnj&userPwd=654321",
                    success:function(msg){
                        alert(msg);
                    },
                    error:function(xhr){
                        alert(xhr.status);
                    }
                });

html代碼 b.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-3.4.1.min.js"></script>
    <!-- 括號裏的ev,ev1,是event事件對象,所有的鼠標移動,鍵盤點擊的詳細狀況都保存在這個形參裏面-->
    <script>
        window.onload=function(ev){
            var oBtn=document.querySelector("button")
            oBtn.onclick=function(ev1){
                $.ajax({
                    type:"GET",
                    url:"a.php",
                    data:"userName=lbj&&userPwd=654321",
                    success:function(msg){
                        alert(msg);
                    },
                    error:function(xhr){
                        alert(xhr.status);
                    }




                    });


                

                }

            }

    </script>

</head>
<body>
<button>發送請求</button>
</body>
</html>

a.php

<?php
echo $_GET["userName"];
echo "<br>";
echo $_GET["userPwd"];

二:封裝自己的Ajax

將jQuery框架包註釋掉,導入自己封裝的js
1.注意,官方的無論是大寫GET還是小寫get,都能傳數據,但是自己的不行,所以還要修改

關鍵代碼:

if(type.toLowerCase()==="get"){//toLowerCase(),如果是小寫,則還是小寫,如果是大寫則轉換成小寫

這樣在html中,無論是get還是GET都能提交數據了

2.在jQuery框架中,參數的順序被打亂之後不會影響,是從對象中取參數,調用者不用擔心請求順序的問題了
HTML代碼 b.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
<!--    <script src="js/jquery-3.4.1.min.js"></script>-->
    <script src="d.js"></script>
    <!-- 括號裏的ev,ev1,是event事件對象,所有的鼠標移動,鍵盤點擊的詳細狀況都保存在這個形參裏面-->
    <script>
        window.onload=function(ev){
            var oBtn=document.querySelector("button")
            oBtn.onclick=function(ev1){
               Ajax({
                  url: "a.php",
                data:{
                   "userName": "'lnj",
                   "userPwd": "123456"
               },
                   type:"GET",
                   timeout: 3000,

                   success:function(xhr) {
                       alert(xhr.responseText);
                   },
                   error:function(xhr) {
                    alert("請求失敗");
                }
                    });


                

                }

            }

    </script>

</head>
<body>
<button>發送請求</button>
</body>
</html>

js代碼 d.js

function objtostr(data){
    /*
            "userName":"lnj",
            "userPwd":"123456"
            "t":"16461231654"
    */
   data.t=new Date().getTime();
    var res=[];
    for(var key in data){
        //在url中是不可以出現中文的,如果出現了中文需要轉碼
        //可以調用encodeURIComponent方法
        //URL中只可以出現字母/數字/下劃線/ASCII碼
        res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key]));//[userName=lnj,userPwd=123456];
    }
    return res.join("&");//join方法把數組轉換成字符串 ,並且元素與元素之間用&連接 userName=lnj&&userPwd=123456
}
function Ajax(option){
    //0.將對象轉換爲字符串
    var str=objtostr(option.data);
    /*三個會變的作爲參數 地址,成功要執行的回調函數,失敗的函數*/
    //兼容IE
    //1.創建一個異步對象
    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.設置請求方式和請求地址(給創建的異步對象設置)
    /*
    method:請求的類型:GET或POST
    url:文件在服務器上的位置
    async:true(異步)或false(同步)  AJAX是異步請求,所以括號裏永遠填true
    */
    if(option.type.toLowerCase()==="get"){//toLowerCase(),如果是小寫,則還是小寫,如果是大寫則轉換成小寫
        xmlhttp.open(option.type,option.url+"?"+str,true)
        //3.發送請求  異步對0象發送請求
        xmlhttp.send();
    }else{
        xmlhttp.open(option.type,option.url,true)
        //注意點:以下代碼必須放到open和send之間
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send(str);
    }

    //4.監聽狀態的變化  監聽的是異步對象的變化  只要異步請求發生了變化,就調用這個回調函數,代表請求已經完成
    xmlhttp.onreadystatechange=function(ev2){
        if(xmlhttp.readyState===4){
            clearInterval(timer);//接收到了響應,把定時器關掉
            /*
            存有 XMLHttpRequest 的狀態。從 0 到 4 發生變化。

           0: 請求未初始化
           1: 服務器連接已建立
           2: 請求已接收
           3: 請求處理中
           4: 請求已完成,且響應已就緒

            */
            //判斷是否請求成功  http狀態碼
            if(xmlhttp.status>=200&&xmlhttp.status<300||
                xmlhttp.status===304){
                //5.處理返回的結果
                /*
                服務器響應
                responseText獲得字符串形式的響應數據
                responseXML 獲得XML形式的響應數據
                */
               option.success(xmlhttp);
            }else{
                option.error(xmlhttp);
            }

        }
    }
    //判斷外界是否傳入了超時時間
    if(option.timeout){
        timer=setInterval(function(){
            console.log("中斷請求");
            xmlhttp.abort();//中斷請求
            clearInterval(timer);
        },option.timeout);
    }
}

php代碼 a.php

<?php
echo $_GET["userName"];
echo "<br>";
echo $_GET["userPwd"];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章