ajax的get和post请求工具类:
/**
* 公共方法类
*
* 使用 变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量
*/
var Common = function() {
/*
* 获取url参数
*/
var getQueryStr = function(sUrlParam, sArgName) {
var retval = "";
if (sUrlParam == null || sUrlParam.length == 0) {
return retval;
}
var args = sUrlParam.split("&");
for (var i = 0; i < args.length; i++) {
sUrlParam = args[i];
var arg = sUrlParam.split("=");
if (arg.length <= 1)
continue;
if (arg[0] == sArgName)
retval = arg[1];
}
return retval;
}
/*
* ajax发送post请求
*/
var postReq = function(url, param, fnCallback, isIndex) {
var target, options = {
title : "异常信息",
content : "",
bodyType : "errorMessage"
};
if (isIndex) {
target = window;
}
else {
target = window.parent;
}
$.ajax({
url : url,
type : "POST",
timeout : 300000,
headers:"Access-Control-Allow-Origin:*",
contentType : "application/x-www-form-urlencoded;charset=UTF-8",
dataType : "json",
data : param
}).done(function(data, textStatus, jqXHR) {
if (jqXHR.getResponseHeader('sessionStatus') == 'timeout') {
options.content = '会话已经超时.';
target.showModal(options, function() {
target.location.href = 'login.html';
});
}
else if (!data) {
options.content = '无返回信息.';
target.showModal(options, function() {
// donothing
});
}
else {
fnCallback(data);
}
}).fail(function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 0) {
options.content = '请求异常,网络连接失败!';
}
else if (jqXHR.status == 403) {
options.content = jqXHR.responseJSON.message;
}
else {
options.content = "请求异常,状态码:" + jqXHR.status;
}
target.showModal(options, function() {
// donothing
});
});
};
var postReq = function(url, param, fnCallback, isIndex) {
var target, options = {
title : "异常信息",
content : "",
bodyType : "errorMessage"
};
if (isIndex) {
target = window;
}
else {
target = window.parent;
}
$.ajax({
url : url,
type : "POST",
timeout : 300000,
contentType : "application/x-www-form-urlencoded;charset=UTF-8",
dataType : "json",
data : param
}).done(function(data, textStatus, jqXHR) {
if (jqXHR.getResponseHeader('sessionStatus') == 'timeout') {
options.content = '会话已经超时.';
target.showModal(options, function() {
target.location.href = 'login.html';
});
}
else if (!data) {
options.content = '无返回信息.';
target.showModal(options, function() {
// donothing
});
}
else {
fnCallback(data);
}
}).fail(function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 0) {
options.content = '请求异常,网络连接失败!';
}
else if (jqXHR.status == 403) {
options.content = jqXHR.responseJSON.message;
}
else {
options.content = "请求异常,状态码:" + jqXHR.status;
}
target.showModal(options, function() {
// donothing
});
});
};
return {
getQueryStr : getQueryStr,
postReq : postReq
}
}();
调用方法:
Common.postReq('svcinfo/findForSelect.do', {
svcAlias : key
}, function(json) {
if ($.trim(key) == '') {
// splice(a1,a2,a3...)从a1位置开始替换a2个元素为a3...
json.data.splice(0, 0, {
svnName : 'all',
svcAlias : '所有服务'
});
}
me.cacheDataSource = [];//清空原数组,避免内存泄露
me.cacheDataSource[key] = json.data;
query.callback({
results : json.data
});
});