每次都寫一堆.ajax,真的很麻煩。因此封裝在一個模塊中比較好。
第一,ajax調用出錯時,自動彈出錯誤對話框,對話框使用的artDialog。
第二,提供基本的post,get簡單調用方式。參數有限,適合就好。
第三,支持中英文。
下面是我的代碼,大家可以自己擴充:
(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 function and except the returned data type is json
// handler(msg) will be callback when .ajax succeeded
// errorHandler(jqXHR, textStatus) willl be callback if .ajax failed
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
// handler(msg) will be callback when .ajax succeeded
// errorHandler(jqXHR, textStatus) willl be callback if .ajax failed
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
// handler(msg) will be callback when .ajax succeeded
// errorHandler(jqXHR, textStatus) willl be callback if .ajax failed
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是ajax請求成功後的回調函數。調用者自己實現。
最後一個參數,如果沒有傳遞,就使用默認的錯誤處理函數,否則就使用調用者自己的函數。