Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

封裝可複用的 jQuery Ajax 呼叫模組

每次到處寫一堆 .ajax 真的很麻煩,把它收攏到一個模組裡會清爽很多。這個模組有三個設計目標:

  1. Ajax 呼叫出錯時自動彈出錯誤對話框,對話框使用 artDialog。
  2. 提供基本的 post、get 簡易呼叫方式,參數不多,够用就好。
  3. 支援中英文。
(function (window, document, undefined) {
 "use strict";
 window.ajaxCall = {

  parameterErrorInfo: "",

  cancelText: "",

  // language should be either 'cn' or 'en'
  init: function (language) {
   window.ajaxCall.language = language;
   if (language === "cn") {
    window.ajaxCall.parameterErrorInfo = "參數數目必須為 5 或者 6";
    window.ajaxCall.cancelText = "取消";
   } else {
    window.ajaxCall.parameterErrorInfo = "Parameters number must be 5 or 6";
    window.ajaxCall.cancelText = "Cancel";
   }
  },

  // popup an error dialog
  defualtErrorHandler: function (jqXHR, textStatus) {
   $.dialog({
    icon: "error",
    content: "Ajax request got an error:" + textStatus,
    cancelVal: window.ajaxCall.cancelText,
    ok: function () {
     this.close();
    }
   });
  },

  // execute .ajax and expect the returned data type is json
  // handler(msg) 在成功時被回呼
  // errorHandler(jqXHR, textStatus) 在失敗時被回呼
  exe: function (urlPath, asyncWay, method, dataValue, handler, errorHandler) {
   var error, request;
   if (arguments.length === 5) {
    error = window.ajaxCall.defaultErrorHandler;
   } else if (arguments.length === 6) {
    error = errorHandler;
   } else {
    $.dialog({
     icon: "error",
     content: window.ajaxCall.parameterErrorInfo,
     cancelVal: window.ajaxCall.cancelText,
     ok: function () {
      this.close();
     }
    });
   }
   request = $.ajax({
    url: urlPath,
    async: asyncWay,
    type: method,
    dataType: 'json',
    data: dataValue
   });
   request.done(handler);
   request.fail(error);
  },

  // post data to server using .ajax
  post: function (urlPath, asyncWay, dataValue, handler, errorHandler) {
   window.ajaxCall.exe(urlPath, asyncWay, 'POST', dataValue, handler, errorHandler);
  },

  // call web method with GET to server using .ajax
  get: function (urlPath, asyncWay, dataValue, handler, errorHandler) {
   window.ajaxCall.exe(urlPath, asyncWay, 'GET', dataValue, handler, errorHandler);
  }
 };

}(window, document));

呼叫方式

先初始化:

window.ajaxCall.init("cn")

再發請求:

window.ajaxCall.post("queryLog", true, data, window.log.fillLog);

其中 window.log.fillLog 是請求成功後的回呼函式,由呼叫者自行實作。最後一個參數 errorHandler 若不傳,就使用模組內建的錯誤處理;傳了則使用呼叫者自己的。

用 IIFE 包住整個模組並只對 window 暴露一個 ajaxCall,可以避免污染全域命名空間。若後續要擴充,建議把「參數個數檢查」改成正规的 options 物件,比依賴 arguments.length 更好維護。

Copyright © Linux教程網 All Rights Reserved