1. 程式人生 > 其它 >定義自己的ajax函式

定義自己的ajax函式

由於用原生js的方式發起的網路請求,都是以查詢字串的形式,提交給伺服器的,使用者以物件的形式提交引數的話會比較方便,所以需要把使用者傳遞過來的引數物件進行處理,定義resolveData的函式,設定形參接收引數,遍歷裡面的物件,把鍵和值用=的方式進行拼接,然後把所得的值新增進空的陣列即可;最後用&符號把陣列的每一項進行分割,並返回;定義itheima函式,設定形參用於接收使用者傳遞過來的配置物件引數,建立xhr物件,把傳遞過來的引數傳遞給處理引數的函式,把得到的返回值,給一個變數,由於是不同的請求,所以要進行判斷,首先是GET請求,判斷引數裡面的method是否全等於GET,由於傳遞過來的引數有可能是小寫,所以通過toUpperCase方法轉化為大寫,如果條件成立呼叫open方法,把對應的值填入即可,呼叫send函式;POST也一樣,只是提交資料多了引數和POST請求需要“Content-Type”頭指定請求主題的MIME型別。最後呼叫監聽事件即可;

function resolveData(data) {
    var arr = [];
    for (var k in data) {
        var str = k + "=" + data[k];
        arr.push(str)
    }
    return arr.join("&")
}

function itheima(options) {
    var xhr = new XMLHttpRequest();
    var qs = resolveData(options.data);
  
    if (options.method.toUpperCase() === "GET") {
        xhr.open(options.method, options.url 
+ "?" + qs); xhr.send(); } else if(options.method.toUpperCase() === "POST"){ xhr.open(options.method, options.url) xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded") xhr.send(qs) } xhr.onreadystatechange = function () { if
(xhr.readyState === 4 && xhr.status === 200) { var result = JSON.parse(xhr.responseText) options.success(result); } } }

最後測試一下是否能成功~

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>測試介面</title>
<script src="itheima.js"></script>
</head>
<body>
    <script>
        itheima({
            method:"GET",
            url:"http://www.liulongbin.top:3006/api/getbooks",
            data:{
                id:1
            },
            success:function(res){
                console.log(res);
            }
        });
    </script>
</body>
</html>

測試成功!有不對的地方,請大家多多指教提醒謝謝!