每次到處寫一堆 .ajax 真的很麻煩,把它收攏到一個模組裡會清爽很多。這個模組有三個設計目標:
(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 更好維護。