每次都写一堆.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请求成功后的回调函数。调用者自己实现。
最后一个参数,如果没有传递,就使用默认的错误处理函数,否则就使用调用者自己的函数。