萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery AJAX 二次封裝:簡化調用、統一錯誤處理與類型安全

項目中重複編寫 `$.ajax` 配置不僅冗余,還易導致參數不一、錯誤處理缺失。本文展示如何將 AJAX 二次封裝為通用工具函數,支持 JSON/文本/HTML 多類型、統一 Loading/錯誤提示、TypeScript 類型定義。

封裝目標

  • 統一請求配置(超時、Headers、Credentials)
  • 標準化響應格式與錯誤處理
  • 支持多種 dataType 自動轉換
  • 提供 Loading 狀態管理
  • TypeScript 類型安全

核心封裝代碼 (ES6 + TypeScript)


// types/ajax.d.ts
interface AjaxOptions {
    url: string;
    type?: "GET" | "POST" | "PUT" | "DELETE";
    data?: any;
    dataType?: "json" | "text" | "html" | "xml" | "script";
    headers?: Record;
    timeout?: number;
    showLoading?: boolean;
    loadingText?: string;
    success?: (data: T, status: string, xhr: JQueryXHR) => void;
    error?: (xhr: JQueryXHR, status: string, error: string) => void;
    complete?: (xhr: JQueryXHR, status: string) => void;
}

interface ApiResponse {
    success: boolean;
    code?: number;
    message?: string;
    data?: T;
}

// utils/ajax.js
class AjaxClient {
    constructor(defaultOptions = {}) {
        this.defaults = {
            type: "POST",
            dataType: "json",
            timeout: 30000,
            showLoading: true,
            loadingText: "處理中...",
            headers: {
                "X-Requested-With": "XMLHttpRequest"
            },
            ...defaultOptions
        };
        this.loadingCount = 0;
        this.$loadingEl = null;
    }

    // 創建 Loading 元素
    createLoadingEl(text) {
        if (this.$loadingEl) return this.$loadingEl;
        this.$loadingEl = $(`
            
${text}
`).appendTo("body"); return this.$loadingEl; } showLoading(text) { if (++this.loadingCount === 1) { this.createLoadingEl(text).show(); } } hideLoading() { if (--this.loadingCount <= 0) { this.loadingCount = 0; this.$loadingEl?.hide(); } } // 核心請求方法 request(options) { const opts = $.extend(true, {}, this.defaults, options); const {showLoading, loadingText, success, error, complete, ...ajaxOpts} = opts; // 顯示 Loading if (showLoading) this.showLoading(loadingText); return $.ajax({ ...ajaxOpts, success: (data, status, xhr) => { // 統一業務邏輯判斷 if (data && data.success === false) { // 後端約定:success=false 表示業務失敗 this.handleError(data.message || "操作失敗", xhr, status, error); return; } success?.(data, status, xhr); }, error: (xhr, status, err) => { this.handleError(this.getErrorMessage(xhr, status, err), xhr, status, error); }, complete: (xhr, status) => { if (showLoading) this.hideLoading(); complete?.(xhr, status); } }); } getErrorMessage(xhr, status, err) { if (status === "timeout") return "請求超時,請檢查網絡"; if (status === "parsererror") return "響應數據格式錯誤"; if (xhr.status === 0) return "網絡連接失敗"; if (xhr.status === 401) return "登錄已過期,請重新登錄"; if (xhr.status === 403) return "無權限訪問"; if (xhr.status >= 500) return "服務器內部錯誤"; return `請求失敗 (${xhr.status}): ${err}`; } handleError(message, xhr, status, errorCallback) { // 統一錯誤提示(可接入項目 Toast/Message 組件) console.error("[AJAX Error]", message, {xhr, status}); // 假設有全局提示組件 if (window.$message) window.$message.error(message); else alert(message); errorCallback?.(xhr, status, message); } // 便捷方法 get(url, data, options) { return this.request({...options, url, type: "GET", data}); } post(url, data, options) { return this.request({...options, url, type: "POST", data}); } put(url, data, options) { return this.request({...options, url, type: "PUT", data}); } delete(url, data, options) { return this.request({...options, url, type: "DELETE", data}); } } // 全局實例 window.ajax = new AjaxClient({ // 項目級默認配置 baseURL: "/api" // 可在 request 中自動拼接 });

CSS Loading 樣式


.ajax-loading-overlay {
    display: none;
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    background: rgba(255,255,255,0.85);
    z-index: 9999;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}
.spinner {
    width: 40px; height: 40px;
    border: 3px solid #e0e0e0;
    border-top-color: #3498db;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}
.loading-text { margin-top: 12px; color: #666; font-size: 14px; }
@keyframes spin { to { transform: rotate(360deg); } }

使用示例

基礎 GET/POST


// GET 請求
ajax.get("/users", {page: 1, size: 20})
    .done(users => renderUserList(users.data));

// POST 提交表單
ajax.post("/users", formData)
    .done(result => {
        if (result.success) {
            $message.success("創建成功");
            closeModal();
        }
    });

自定義配置


// 文件上傳(不設置 Content-Type,由瀏覽器自動設置 boundary)
ajax.request({
    url: "/upload",
    type: "POST",
    data: formData,
    processData: false, // 關鍵:不序列化 FormData
    contentType: false,
    showLoading: true,
    loadingText: "上傳中...",
    success: res => console.log(res)
});

// 禁用 Loading(如輪詢接口)
ajax.get("/status", {}, {showLoading: false});

// 覆寫錯誤處理(靜默失敗)
ajax.post("/log", logData, {
    error: () => {}, // 靜默
    showLoading: false
});

進階:請求/響應攔截器模式


class InterceptableAjax extends AjaxClient {
    constructor() {
        super();
        this.requestInterceptors = [];
        this.responseInterceptors = [];
    }

    addRequestInterceptor(fn) { this.requestInterceptors.push(fn); }
    addResponseInterceptor(fn) { this.responseInterceptors.push(fn); }

    request(options) {
        // 請求攔截鏈
        let promise = Promise.resolve(options);
        this.requestInterceptors.forEach(fn => {
            promise = promise.then(fn);
        });

        return promise.then(finalOpts => {
            const jqXhr = super.request(finalOpts);

            // 響應攔截鏈(包裝 Promise)
            return new Promise((resolve, reject) => {
                jqXhr.done((data, status, xhr) => {
                    let result = {data, status, xhr};
                    this.responseInterceptors.forEach(fn => result = fn(result) || result);
                    resolve(result.data);
                }).fail((xhr, status, err) => reject({xhr, status, err}));
            });
        });
    }
}

// 使用:自動添加 Token
ajax.addRequestInterceptor(opts => {
    opts.headers = {...opts.headers, Authorization: "Bearer " + getToken()};
    return opts;
});

// 使用:統一處理 401 登出
ajax.addResponseInterceptor(result => {
    if (result.xhr.status === 401) {
        logoutAndRedirect();
    }
    return result;
});

遷移指南:從零散 $.ajax 到統一封裝

  1. 創建 `ajax.js` 引入項目
  2. 全局搜索 `$.ajax(` 逐個替換為 `ajax.get/post/request`
  3. 統一錯誤提示風格(接入項目 Message 組件)
  4. 添加 TypeScript 定義文件獲得 IDE 提示
  5. 配置 ESLint 禁止直接使用 `$.ajax`

二次封裝 AJAX 不僅減少樣板代碼,更能建立項目級的網絡請求規範,為後續接入請求緩存、重試、離線隊列等高級功能奠定基礎。

copyright © 萬盛學電腦網 all rights reserved