1. 程式人生 > 其它 >封裝原生Ajax函式

封裝原生Ajax函式

先分享一篇優秀博文:Ajax函式的封裝

ajax.js程式碼

function ajax(options) {
    // 1 建立Ajax物件
    let xhr = new XMLHttpRequest();
    // 拼接請求引數變數
    let params = '';
    for (let attr in options.data) {
        params += attr + '=' + options.data[attr] + '&';
    }

    // 對字串進行擷取
    // 將引數最後面的 & 擷取掉
    // 將擷取的結果重新賦值給params變數
params = params.substring(0, params.length - 1); // console.log(params) // 判斷請求方式 if (options.type == 'get') { options.url = options.url + '?' + params; } // 告訴Ajax請求地址及其方式 xhr.open(options.type, options.url); // 如果請求方式為post if (options.type == 'post') {
// 使用者希望的向伺服器端傳遞的請求引數的型別 let contentType = options.header['Content-Type']; // 設定請求引數格式的型別 xhr.setRequestHeader('Content-Type', contentType); // 判斷使用者希望的請求引數格式的型別 // 如果型別為json if (contentType == 'application/json') { // 向伺服器端傳遞json資料格式的引數 xhr.send(JSON.stringify(options.data)); }
else { // 向伺服器端傳遞普通型別的請求引數 xhr.send(params); } } else { // 3 傳送請求 post請求要把請求引數放在請求體裡面偶! xhr.send(); } // 4 獲取伺服器端響應給客戶端的資料[也就是監聽onload事件!] xhr.onload = function() { // xhr.getResponseHeader() // 獲取響應頭中的資料! // 根據你請求方式不同而返回不一樣的結果! let contentType = xhr.getResponseHeader('Content-Type'); // 伺服器端返回的資料 let responseText = xhr.responseText; // 如果響應型別中包含json if (contentType.includes('application/json')) { // console.log('包含'); // console.log(JSON.parse(responseText)); //將json字串轉換為json物件 responseText = JSON.parse(responseText); } else { } if (xhr.status == 200) { // 請求成功呼叫處理成功情況的函式 options.success(responseText); } else { // 請求失敗呼叫處理失敗情況的函式 options.error(responseText, xhr); } } }

呼叫示例:

<body>
    <!-- <h1>## Ajax的實現步驟</br> -->
    <h1>測試頁面!</h1>
    <button id="btn">Ajax錯誤處理</button>
    <script type="text/javascript">
        let btn = document.getElementById('btn');
        btn.onclick = function() {
            ajax({
                type: 'post',
                data: {
                    name: 'zrh',
                    age: 23
                },
                header: {
                    'Content-Type': 'application/json'
                },
                url: 'https://v1.alapi.cn/api/music/search?keyword=1',
                success: function(data) {
                    console.log("這是封裝的響應結果" + data);
                    console.log(data);
                },
                error: function(data, xhr) {
                    console.log('恭喜您收到了一個非200的狀態碼' + data);
                    console.log(xhr);
                }
            })
        }
    </script>
</body>