您的位置:首页 > Web前端 > JQuery

复用jquery的ajax调用模块

2012-12-15 19:04 246 查看
每次都写一堆.ajax,真的很麻烦。因此封装在一个模块中比较好。
第一,ajax调用出错时,自动弹出错误对话框,对话框使用的artDialog。
第二,提供基本的post,get简单调用方式。参数有限,适合就好。
第三,支持中英文。
下面是我的代码,大家可以自己扩充:
require.config({
paths: {
"jquery": "../thirdParty/jquery-1.8.0.min",
"dialog": "./dialog"
}
});

define("ajaxUtility", ["jquery", "dialog"], function ($, dialog) {
'use strict';

return {
cancelText: "",

language: "",

// language should be either 'cn' or 'en'
init: function (language) {
this.language = language;
dialog.init(language);
if (this.language === "cn") {
this.cancelText = "取消";
} else {
this.cancelText = "Cancel";
}
},

// popup an error dialog
defualtErrorHandler: function (jqXHR, textStatus) {
dialog.error("Ajax request got an error:" + textStatus);
},

// 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, context) {
var error, request;
if (errorHandler) {
error = errorHandler;
} else {
error = this.defaultErrorHandler;
}
request = $.ajax({
url: urlPath,
async: asyncWay,
type: method,
dataType: 'json',
data: dataValue
});

// request.done only calls function(msg), but we can use
// closure to pass ob and hdl arguments
request.done(
(function (ob, hdl) {
return function (msg) {
hdl(ob, msg);
};
}(context, handler))
);
request.fail(error);
},

// post data to server using .ajax
// handler(ob, msg) will be callback when .ajax succeeded
// errorHandler(jqXHR, textStatus) willl be callback if .ajax failed
post: function (urlPath, asyncWay, dataValue, handler, errorHandler, context) {
this.exe(urlPath, asyncWay, 'POST', dataValue, handler, errorHandler, context);
},

// call web method with GET to server using .ajax
// handler(ob, msg) will be callback when .ajax succeeded
// errorHandler(jqXHR, textStatus) willl be callback if .ajax failed
get: function (urlPath, asyncWay, dataValue, handler, errorHandler, context) {
this.exe(urlPath, asyncWay, 'GET', dataValue, handler, errorHandler, context);
}
};
});


调用很简单:
data = {
'ids': ids,
'message': content,
'length': content.length,
"groupId": $("#groupsSel").val(),
"excludes": this.excludesToString(),
"includes": this.includesToString(),
"baseOp": this.baseOp
};

this.ajaxUtility.post('saveDigitalMessage', false, data, this.afterSaveDigitMessage, null, this);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: