前端一些常用的工具类
-
-
- ip
- 封装ajax工具类
- 日期工具类
- 数据工具类
- 时间工具类
- 上述工具类extends.js
- 工具类
ip
IPUtils = {
//IP转数字
ip2int: function (ip) {
var num = 0;
ip = ip.split(".");
num = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3]);
num = num >>> 0;
return num;
},
//数字转IP
int2iP: function (num) {
var str;
var tt = new Array();
tt[0] = (num >>> 24) >>> 0;
tt[1] = ((num << 8) >>> 24) >>> 0;
tt[2] = (num << 16) >>> 24;
tt[3] = (num << 24) >>> 24;
str = String(tt[0]) + "." + String(tt[1]) + "." + String(tt[2]) + "." + String(tt[3]);
return str;
},
//列出IP段内的IP
listIP: function (ip1, ip2) {
var ipInt1 = this.ip2int(ip1);
var ipInt2 = this.ip2int(ip2);
var arr = new Array();
var index = 0;
for (var i = ipInt1; i <= ipInt2; i++) {
arr[index] = this.int2iP(i);
index++;
}
return arr;
}
}
封装ajax工具类
AjaxUtils = {
doError: function (error_f, XMLHttpRequest) {
if (XMLHttpRequest.status == "403") {
// console.info($(parent.document).find("meta[name='keywords']").attr("content"));
if (error_f) {
error_f("你没有操作权限");
} else {
if ($("meta[name='keywords']").attr("content") == "HOME") {
bootbox.alert("你没有操作权限");
} else {
parent.bootbox.alert("你没有操作权限");
}
}
} else if (XMLHttpRequest.status == "0") {
if (error_f) {
bootbox.alert({
size: 'small',
message: '网络错误',
callback: function () {
error_f();
}
});
}
} else if (XMLHttpRequest.status == "400") {
bootbox.alert("Bad Resq");
}
},
sendForm: function (formId, success_f, fail_f, error_f) {
var options = {
success: function (result) {
if (result.success) {
if (success_f) {
success_f(result);
}
} else {
if (fail_f) {
fail_f(result);
}
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
AjaxUtils.doError(error_f, XMLHttpRequest);
}
};
$("#" + formId).ajaxForm(options);
},
sendFormData: function (url, data, success_f, fail, error_f) {
$.ajax({
url: url,
type: 'POST',
data: data,
contentType: false,
processData: false,
cache: false,
success: function (result) {
if (result.success) {
if (success_f) {
success_f(result);
} else {
bootbox.alert({
message: result.msg,
size: 'small',
});
}
} else {
if (fail) {
fail(result);
}
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
AjaxUtils.doError(error_f, XMLHttpRequest);
},
});
},
sendResq: function (url, type, data, success_f, fail, error_f) {
$.ajax({
url: url,
type: type,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.success) {
if (success_f) {
success_f(result);
}
} else {
if (fail) {
fail(result);
}
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
AjaxUtils.doError(error_f, XMLHttpRequest);
},
});
},
}
日期工具类
dateUtils : {
addDay : function(date, amount) {
date.setDate(date.getDate() + amount);
return date;
},
stampToTime : function(timestamp) {
//时间戳为10位需*1000,时间戳为13位的话不需乘1000
var date = new Date(timestamp);
var Y = date.getFullYear() + '-';
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
var D = date.getDate() + ' ';
var h = date.getHours() + ':';
var m = date.getMinutes() + ':';
var s = date.getSeconds();
return Y + M + D + h + m + s;
},
stampToDate : function(timestamp) {
var newDate = new Date(); //实例化一个Date对象
newDate.setTime(timestamp); //设置Date对象的时间为时间戳的时间
return newDate;
},
compare : function(date1, date2) {
if (date1.getTime() > date2.getTime()) {
return true;
} else {
return false;
}
},
second2Time : function(second_time) {
second_time = parseFloat(second_time) / 1000;
var time = parseInt(second_time) + "秒";
if (parseInt(second_time) > 60) {
// var second = parseInt(second_time) % 60;
var min = parseInt(second_time / 60);
time = min + "分";
if (min > 60) {
min = parseInt(second_time / 60) % 60;
var hour = parseInt(parseInt(second_time / 60) / 60);
time = hour + "小时" + min + "分";
if (hour > 24) {
hour = parseInt(parseInt(second_time / 60) / 60) % 24;
var day = parseInt(parseInt(parseInt(second_time / 60) / 60) / 24);
time = day + "天" + hour + "小时" + min + "分";
}
}
}
return time;
},
isBeforeCurrentTime : function(value) {
var myDate = new Date();
var now = myDate.valueOf();
var time = new Date(value).valueOf();
if (now > time) {
return true;
} else {
return false;
}
},
add0 : function(m) {
return m < 10 ? '0' + m : m;
},
format : function(shijianchuo) {
// shijianchuo是整数,否则要parseInt转换
var time = new Date(shijianchuo);
var y = time.getFullYear();
var m = time.getMonth() + 1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
return y + '-' + this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h)
+ ':' + this.add0(mm) + ':' + this.add0(s);
},
formatter : function(date) {
date = new Date(date);
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
var h = date.getHours();
var mi = date.getMinutes();
var s = date.getSeconds();
return y + '-' + (m < 10 ? ('0' + m) : m) + '-'
+ (d < 10 ? ('0' + d) : d) + " " + (h < 10 ? ('0' + h) : h) + ":" + (mi < 10 ? ('0' + mi) : mi) + ":" + (s < 10 ? ('0' + s) : s);
},
// 获取指定时间的后60秒
getAfterOneMin : function() {
date.setHours(date.getMinutes() + 1);
return this.formatter(date);
},
// 获取指定时间的前60秒
getAfterOneMin : function() {
date.setHours(date.getMinutes() - 1);
return this.formatter(date);
},
// 返回指定时间是否在当前时间的左右1分钟区间内
isBetweenTheOneMin : function(date) {
var myData = new Date(date);
var now = new Date();
if ((myData > now.setMinutes(now.getMinutes() - 1))
&& (myData < now.setMinutes(now.getMinutes() + 1))) {
return true;
} else {
return false;
}
},
getRecentHour : function(dateParam) {
if (!dateParam) {
var now = new Date();
var date = new Date(now.getTime() - 1 * 3600 * 1000);
return [ this.formatter(date), this.formatter(now) ];
} else {
var firstDate = new Date(dateParam + ":00:00");
firstDate.setMinutes(0);
firstDate.setSeconds(0);
var endDate = new Date(dateParam + ":00:00");
endDate.setMinutes(59);
endDate.setSeconds(59);
return [ this.formatter(firstDate), this.formatter(endDate) ];
}
},
getRecentDate : function(dateParam) {
if (!dateParam) {
var now = new Date();
var date = new Date(now.getTime() - 24 * 3600 * 1000);
return [ this.formatter(date), this.formatter(now) ];
} else {
var firstDate = new Date(dateParam);
firstDate.setHours(0);
firstDate.setMinutes(0);
firstDate.setSeconds(0);
var endDate = new Date(dateParam);
endDate.setHours(23);
endDate.setMinutes(59);
endDate.setSeconds(59);
return [ this.formatter(firstDate), this.formatter(endDate) ];
}
},
getRecentWeek : function(dateParam) {
if (!dateParam) {
var now = new Date();
var date = new Date(now.getTime() - 7 * 24 * 3600 * 1000);
return [ this.formatter(date), this.formatter(now) ];
}
},
getRecentMonth : function(dateParam) {
if (!dateParam) {
var now = new Date();
var date = new Date(now.getTime() - 30 * 24 * 3600 * 1000);
return [ this.formatter(date), this.formatter(now) ];
} else {
var firstDate = new Date(dateParam);
firstDate.setDate(1);
var endDate = new Date(firstDate);
endDate.setMonth(firstDate.getMonth() + 1);
endDate.setDate(0);
firstDate.setHours(0);
firstDate.setMinutes(0);
firstDate.setSeconds(0);
endDate.setHours(23);
endDate.setMinutes(59);
endDate.setSeconds(59);
return [ this.formatter(firstDate), this.formatter(endDate) ];
}
},
},
数据工具类
dataUtils : {
convertStruct : function(arr, objs) {
var obj_arrs = new Array();
for (var i = 0; i < arr.length; i++) {
var objStr = "{";
for (var Key in objs) {
var value = arr[i][objs[Key]];
if (!isNaN(value)) {
objStr = objStr + "\"" +
Key + "\":" + value + ",";
} else {
objStr = objStr + "\"" +
Key + "\":" + "\"" + value + "\",";
}
}
//删除最后的逗号
objStr = objStr.substring(0, objStr.length - 1);
objStr = objStr + "}";
obj_arrs.push(JSON.parse(objStr));
}
for (var i = 2; i < arguments.length; i++) {
obj_arrs.push(arguments[i])
}
return obj_arrs;
}
}
时间工具类
TimeUtils = {
second2Time : function(second_time) {
second_time = parseInt(parseFloat(second_time) / 1000);
var time = "";
var day = 0;
var hour = 0;
var min = 0;
var sec = 0;
sec = second_time % 60;
second_time = parseInt(second_time / 60);
min = second_time % 60;
second_time = parseInt(second_time / 60);
hour = second_time % 24;
second_time = parseInt(second_time / 24);
day = second_time;
if (day != 0)
time += day + "天" + hour + "时" + min + " 分" + sec + "秒";
else if (hour != 0)
time += hour + "时" + min + " 分" + sec + "秒";
else if (min != 0)
time += min + " 分" + sec + "秒";
else
time += sec + "秒";
return time;
},
format : function(shijianchuo) {
// shijianchuo是整数,否则要parseInt转换
var time = new Date(shijianchuo);
var y = time.getFullYear();
var m = time.getMonth() + 1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
return y + '-' + this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h)
+ ':' + this.add0(mm) + ':' + this.add0(s);
},
add0 : function(m) {
return m < 10 ? '0' + m : m;
},
formatter : function(date) {
date = new Date(date);
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
var h = date.getHours();
var mi = date.getMinutes();
var s = date.getSeconds();
return y + '-' + (m < 10 ? ('0' + m) : m) + '-'
+ (d < 10 ? ('0' + d) : d) + " " + h + ":" + mi + ":" + s;
},
// 返回指定时间是否在当前时间的左右1分钟区间内
isBetweenTheOneMin : function(date) {
var myData = new Date(date);
var now = new Date();
if ((myData > now.setMinutes(now.getMinutes() - 1))
&& (myData < now.setMinutes(now.getMinutes() + 1))) {
return true;
} else {
return false;
}
},
}
上述工具类extends.js
window.XAJA = function(url) {
return new _XAJA(url);
}
window.XAJAConfirmProxy = function(callback) {
//使用配置的confirm插件
return new _XAJAConfirmProxy(callback);
}
function _XAJAConfirmProxy(callback) {
this.callback = callback;
}
_XAJAConfirmProxy.prototype = {
setMsg : function(msg) {
this.msg = msg;
return this;
},
exec : function() {
var _this = this;
if (this.msg) {
XAJAConfig.confirmPlugin(this.msg, function() {
_this.callback();
});
} else {
XAJAConfig.confirmPlugin(undefined, function() {
_this.callback();
});
}
}
}
//参数可能为url,也可能为form表单的$元素
function _XAJA(url) {
this.url = url;
//this.isExec = true;
}
//请求的结果只可能有三种,一种是成功,一种是非成功,一种是失败(404,401,500等异常)
这条线开始是更新的核心
_XAJA.prototype = {
//是否自动开启确认操作
confirm : function(callback) {
this._confirm = callback;
if (this.successor) {
this.successor.handle()
}
},
async : function() {
this._async = false;
return this;
},
//传入参数
data : function(data) {
this._data = data;
return this;
},
contentType : function(contentType) {
// this.contentType = "application/x-www-form-urlencoded";
this._contentType = contentType;
return this;
},
//请求前执行的函数(例如显示进度加载条什么的)
before : function(callback) {
this.beforeFUN = callback;
return this;
},
//请求后执行的函数(例如隐藏进度条什么的)
after : function(callback) {
this.afterFUN = callback;
return this;
},
//成功时执行的函数
success : function(callback) {
this.successFUN = callback;
return this;
},
//成功时返回所有数据
success2 : function(callback) {
this.successFUN2 = callback;
return this;
},
//成功后执行的函数(例如关闭进度加载条)
afterSuccess : function(callback) {
this.afterSuccessFUN = callback;
return this;
},
//统一请求错误的处理
innormal : function(callback) {
this.innormalFUN = callback;
return this;
},
//之后
afterInnormal : function(callback) {
this.afterInnormalFUN = callback;
return this;
},
//非成功时执行的函数
unSuccess : function(callback) {
this.unSuccessFUN = callback;
return this;
},
//非成功前执行函数(没用)
beforeUnSuccess : function(callback) {
this.beforeUnSuccessFUN = callback;
return this;
},
//非成功后执行函数(例如关闭进度条什么的)
afterUnSuccess : function(callback) {
this.afterUnSuccessFUN = callback;
return this;
},
//请求服务器后台回应失败的操作(不包括401,404等问题)
doUnsuccess : function(result) {
if (this.unSuccessFUN) {
this.unSuccessFUN(result);
} else {
}
if (this.afterUnSuccessFUN) {
this.afterUnSuccessFUN(result);
} else {
}
},
unifyHandle : function(callback) {
this.unifyHandleFUN = callback;
return this;
},
afterUnifyHandle : function(callback) {
this.afterUnifyHandleFUN = callback;
return this;
},
//一切除了成功之外的任何客户不愿想看到的处理
doUnifyHandle : function(obj) {
var msg;
if (obj.httpStatus) {
msg = XAJAConfig.webCodeMsg[httpStatus.status]
} else {
msg = obj.msg;
}
if (this.unifyHandleFUN) {
this.isDoUnifyHandle = true;
this.unifyHandleFUN(msg);
} else {
}
if (this.afterUnifyHandleFUN) {
this.afterUnifyHandleFUN(msg);
} else {
}
},
//异常处理
doInnormal : function(xhr) {
//先看看是够客户端已经开启了统一处理
this.doUnifyHandle(xhr);
//先看看是够客户端已经开启了统一处理
if (this.isDoUnifyHandle) {
return;
}
if (this.innormalFUN) {
this.innormalFUN(xhr);
} else {
XAJAConfig.innormalTipPlugin(xhr);
}
if (this.afterInnormalFUN) {
this.afterInnormalFUN(xhr);
} else {
//执行配置方法
}
},
//正常处理(成功和非成功)
doNormal : function(result) {
//console.info("请求得到的数据:" + JSON.stringify(result));
// if (this.successFUN) {
// //执行用户自定义方法
// if (result) {
// this.successFUN(result)
// }
// }
if (result[XAJAConfig.successKey] == XAJAConfig.successValue) {
//操作成功
if (this.successFUN2) {
if (result) {
this.successFUN2(result)
}
} else {
if (this.successFUN) {
//执行用户自定义方法
if (result.data!=null) {
this.successFUN(result.data)
} else {
this.successFUN(result.msg);
}
} else {
// 执行默认方法
XAJAConfig.successTipPlugin(result[XAJAConfig.successMsgKey]);
}
}
if (this.afterSuccessFUN) {
if (result.data) {
this.afterSuccessFUN(result.data)
} else {
this.afterSuccessFUN(result.msg);
}
} else {
//执行配置方法
}
} else if (result[XAJAConfig.successKey] == XAJAConfig.unSuccessValue) {
//操作非成功
this.doUnifyHandle(result);
//先看看是够客户端已经开启了统一处理
if (this.isDoUnifyHandle) {
return;
}
if (this.beforeUnSuccessFUN) {
this.beforeUnSuccessFUN(result);
} else {
//执行配置方法
}
if (this.unSuccessFUN) {
//执行用户自定义方法
if (result.data) {
this.unSuccessFUN(result.data)
} else {
this.unSuccessFUN(result.msg);
}
} else {
XAJAConfig.unSuccessTipPlugin(result);
}
if (this.afterUnSuccessFUN) {
this.afterUnSuccessFUN(result);
} else {
//执行配置方法
}
} else {
throw "请求成功但无对应json相应,请检查是否出现重定向或者对应参数问题";
}
},
doBefore : function() {
if (this.beforeFUN) {
this.beforeFUN();
}
},
doAfter : function() {
if (this.afterFUN) {
this.afterFUN();
}
},
confirmGet : function() {
if (_this._confirm) {
}
},
get : function() {
var _this = this;
var contentType = _this._contentType;
var async = _this._async;
if (!contentType) {
contentType = "application/json; charset=utf-8";
}
if (!async) {
async = true;
}
$.ajax({
beforeSend : this.doBefore(),
url : this.url,
type : "GET",
async : async,
data : _this._data,
contentType : contentType,
dataType : "json",
success : function(result) {
_this.doNormal(result);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
_this.doInnormal(XMLHttpRequest);
},
complete : function() {
_this.doAfter();
}
});
},
post : function() {
var _this = this;
var contentType = _this._contentType;
if (!contentType) {
contentType = "application/x-www-form-urlencoded";
}
$.ajax({
beforeSend : this.doBefore(),
url : this.url,
type : "POST",
data : _this._data,
contentType : contentType,
dataType : "json",
success : function(result) {
_this.doNormal(result)
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
_this.doInnormal(XMLHttpRequest);
},
complete : function() {
_this.doAfter();
}
});
},
postJson : function() {
var _this = this;
var contentType = _this._contentType;
if (!contentType) {
contentType = "application/json; charset=utf-8";
}
$.ajax({
beforeSend : this.doBefore(),
url : this.url,
type : "POST",
data : _this._data,
contentType : contentType,
dataType : "json",
success : function(result) {
_this.doNormal(result)
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
_this.doInnormal(XMLHttpRequest);
},
complete : function() {
_this.doAfter();
}
});
},
formData : function() {
var _this = this;
$.ajax({
beforeSend : this.doBefore(),
url : this.url,
type : "POST",
data : _this._data,
contentType : false,
processData : false,
success : function(result) {
_this.doNormal(result)
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
_this.doInnormal(XMLHttpRequest);
},
complete : function() {
_this.doAfter();
}
});
},
form : function() {
var _this = this;
var options = {
beforeSubmit : this.doBefore(),
success : function(result) {
_this.doNormal(result)
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
_this.doInnormal(XMLHttpRequest);
},
complete : function() {
_this.doAfter();
}
};
this.url.ajaxSubmit(options);
}
}
///以下部分是工具类///
$.extend({
UrlUtils : {
getParam : function(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
var context = "";
if (r != null)
context = r[2];
reg = null;
r = null;
return context == null || context == "" || context == "undefined" ? "" : context;
}
},
dateUtils : {
addDay : function(date, amount) {
date.setDate(date.getDate() + amount);
return date;
},
stampToTime : function(timestamp) {
//时间戳为10位需*1000,时间戳为13位的话不需乘1000
var date = new Date(timestamp);
var Y = date.getFullYear() + '-';
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
var D = date.getDate() + ' ';
var h = date.getHours() + ':';
var m = date.getMinutes() + ':';
var s = date.getSeconds();
return Y + M + D + h + m + s;
},
stampToDate : function(timestamp) {
var newDate = new Date(); //实例化一个Date对象
newDate.setTime(timestamp); //设置Date对象的时间为时间戳的时间
return newDate;
},
compare : function(date1, date2) {
if (date1.getTime() > date2.getTime()) {
return true;
} else {
return false;
}
},
second2Time : function(second_time) {
second_time = parseFloat(second_time) / 1000;
var time = parseInt(second_time) + "秒";
if (parseInt(second_time) > 60) {
// var second = parseInt(second_time) % 60;
var min = parseInt(second_time / 60);
time = min + "分";
if (min > 60) {
min = parseInt(second_time / 60) % 60;
var hour = parseInt(parseInt(second_time / 60) / 60);
time = hour + "小时" + min + "分";
if (hour > 24) {
hour = parseInt(parseInt(second_time / 60) / 60) % 24;
var day = parseInt(parseInt(parseInt(second_time / 60) / 60) / 24);
time = day + "天" + hour + "小时" + min + "分";
}
}
}
return time;
},
isBeforeCurrentTime : function(value) {
var myDate = new Date();
var now = myDate.valueOf();
var time = new Date(value).valueOf();
if (now > time) {
return true;
} else {
return false;
}
},
add0 : function(m) {
return m < 10 ? '0' + m : m;
},
format : function(shijianchuo) {
// shijianchuo是整数,否则要parseInt转换
var time = new Date(shijianchuo);
var y = time.getFullYear();
var m = time.getMonth() + 1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
return y + '-' + this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h)
+ ':' + this.add0(mm) + ':' + this.add0(s);
},
formatter : function(date) {
date = new Date(date);
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
var h = date.getHours();
var mi = date.getMinutes();
var s = date.getSeconds();
return y + '-' + (m < 10 ? ('0' + m) : m) + '-'
+ (d < 10 ? ('0' + d) : d) + " " + (h < 10 ? ('0' + h) : h) + ":" + (mi < 10 ? ('0' + mi) : mi) + ":" + (s < 10 ? ('0' + s) : s);
},
// 获取指定时间的后60秒
getAfterOneMin : function() {
date.setHours(date.getMinutes() + 1);
return this.formatter(date);
},
// 获取指定时间的前60秒
getAfterOneMin : function() {
date.setHours(date.getMinutes() - 1);
return this.formatter(date);
},
// 返回指定时间是否在当前时间的左右1分钟区间内
isBetweenTheOneMin : function(date) {
var myData = new Date(date);
var now = new Date();
if ((myData > now.setMinutes(now.getMinutes() - 1))
&& (myData < now.setMinutes(now.getMinutes() + 1))) {
return true;
} else {
return false;
}
},
getRecentHour : function(dateParam) {
if (!dateParam) {
var now = new Date();
var date = new Date(now.getTime() - 1 * 3600 * 1000);
return [ this.formatter(date), this.formatter(now) ];
} else {
var firstDate = new Date(dateParam + ":00:00");
firstDate.setMinutes(0);
firstDate.setSeconds(0);
var endDate = new Date(dateParam + ":00:00");
endDate.setMinutes(59);
endDate.setSeconds(59);
return [ this.formatter(firstDate), this.formatter(endDate) ];
}
},
getRecentDate : function(dateParam) {
if (!dateParam) {
var now = new Date();
var date = new Date(now.getTime() - 24 * 3600 * 1000);
return [ this.formatter(date), this.formatter(now) ];
} else {
var firstDate = new Date(dateParam);
firstDate.setHours(0);
firstDate.setMinutes(0);
firstDate.setSeconds(0);
var endDate = new Date(dateParam);
endDate.setHours(23);
endDate.setMinutes(59);
endDate.setSeconds(59);
return [ this.formatter(firstDate), this.formatter(endDate) ];
}
},
getRecentWeek : function(dateParam) {
if (!dateParam) {
var now = new Date();
var date = new Date(now.getTime() - 7 * 24 * 3600 * 1000);
return [ this.formatter(date), this.formatter(now) ];
}
},
getRecentMonth : function(dateParam) {
if (!dateParam) {
var now = new Date();
var date = new Date(now.getTime() - 30 * 24 * 3600 * 1000);
return [ this.formatter(date), this.formatter(now) ];
} else {
var firstDate = new Date(dateParam);
firstDate.setDate(1);
var endDate = new Date(firstDate);
endDate.setMonth(firstDate.getMonth() + 1);
endDate.setDate(0);
firstDate.setHours(0);
firstDate.setMinutes(0);
firstDate.setSeconds(0);
endDate.setHours(23);
endDate.setMinutes(59);
endDate.setSeconds(59);
return [ this.formatter(firstDate), this.formatter(endDate) ];
}
},
},
downloadUtils : {
download : function(filename, content) {
var a = document.createElement('a');
var blob = new Blob([ content ], {
'type' : 'text/plain;charset=utf-8'
});
var obj_url = window.URL.createObjectURL(blob);
a.href = obj_url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(obj_url);
},
saveFile : function(data, filename) {
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = data;
save_link.download = filename;
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
save_link.dispatchEvent(event);
}
},
dataUtils : {
convertStruct : function(arr, objs) {
var obj_arrs = new Array();
for (var i = 0; i < arr.length; i++) {
var objStr = "{";
for (var Key in objs) {
var value = arr[i][objs[Key]];
if (!isNaN(value)) {
objStr = objStr + "\"" +
Key + "\":" + value + ",";
} else {
objStr = objStr + "\"" +
Key + "\":" + "\"" + value + "\",";
}
}
//删除最后的逗号
objStr = objStr.substring(0, objStr.length - 1);
objStr = objStr + "}";
obj_arrs.push(JSON.parse(objStr));
}
for (var i = 2; i < arguments.length; i++) {
obj_arrs.push(arguments[i])
}
return obj_arrs;
}
}
})
TimeUtils = {
second2Time : function(second_time) {
second_time = parseInt(parseFloat(second_time) / 1000);
var time = "";
var day = 0;
var hour = 0;
var min = 0;
var sec = 0;
sec = second_time % 60;
second_time = parseInt(second_time / 60);
min = second_time % 60;
second_time = parseInt(second_time / 60);
hour = second_time % 24;
second_time = parseInt(second_time / 24);
day = second_time;
if (day != 0)
time += day + "天" + hour + "时" + min + " 分" + sec + "秒";
else if (hour != 0)
time += hour + "时" + min + " 分" + sec + "秒";
else if (min != 0)
time += min + " 分" + sec + "秒";
else
time += sec + "秒";
return time;
},
format : function(shijianchuo) {
// shijianchuo是整数,否则要parseInt转换
var time = new Date(shijianchuo);
var y = time.getFullYear();
var m = time.getMonth() + 1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
return y + '-' + this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h)
+ ':' + this.add0(mm) + ':' + this.add0(s);
},
add0 : function(m) {
return m < 10 ? '0' + m : m;
},
formatter : function(date) {
date = new Date(date);
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
var h = date.getHours();
var mi = date.getMinutes();
var s = date.getSeconds();
return y + '-' + (m < 10 ? ('0' + m) : m) + '-'
+ (d < 10 ? ('0' + d) : d) + " " + h + ":" + mi + ":" + s;
},
// 返回指定时间是否在当前时间的左右1分钟区间内
isBetweenTheOneMin : function(date) {
var myData = new Date(date);
var now = new Date();
if ((myData > now.setMinutes(now.getMinutes() - 1))
&& (myData < now.setMinutes(now.getMinutes() + 1))) {
return true;
} else {
return false;
}
},
}
//扩展这个serializeArray,让其支持得到未选择的checkbox
$.fn.serializeAll = function() {
var formObj = this.serializeArray();
formObj = formObj.concat(
jQuery('input[type=checkbox]:not(:checked)', this).map(
function() {
return {
"name" : this.name,
"value" : "0"
}
}).get()
);
return formObj;
};
IPUtils = {
//IP转数字
ip2int : function(ip) {
var num = 0;
ip = ip.split(".");
num = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3]);
num = num >>> 0;
return num;
},
//数字转IP
int2iP : function(num) {
var str;
var tt = new Array();
tt[0] = (num >>> 24) >>> 0;
tt[1] = ((num << 8) >>> 24) >>> 0;
tt[2] = (num << 16) >>> 24;
tt[3] = (num << 24) >>> 24;
str = String(tt[0]) + "." + String(tt[1]) + "." + String(tt[2]) + "." + String(tt[3]);
return str;
},
//列出IP段内的IP
listIP : function(ip1, ip2) {
var ipInt1 = this.ip2int(ip1);
var ipInt2 = this.ip2int(ip2);
var arr = new Array();
var index = 0;
for (var i = ipInt1; i <= ipInt2; i++) {
arr[index] = this.int2iP(i);
index++;
}
return arr;
}
}
MYUtils = {
isEmpty : function(value) {
if (!value) {
return true;
} else if (value == null) {
return true;
} else if (value == "") {
return true;
} else {
return false;
}
}
}
ArrayUtils = {
unique : function(arr, field) {
var newArr = new Array();
for (var i = 0; i < arr.length; i++) {
newArr.push(arr[i][field]);
}
var result = [],
hash = {};
for (var i = 0, elem; (elem = newArr[i]) != null; i++) {
if (!hash[elem]) {
result.push(elem);
hash[elem] = true;
}
}
return result;
}
}
var MYCONSTANS = {
regex : {
valiIP : /^((1?\d?\d|(2([0-4]\d|5[0-5])))\.){3}(1?\d?\d|(2([0-4]\d|5[0-4])))$/,
valiIPRange : /^(((1?\d?\d|(2([0-4]\d|5[0-5])))\.){3}(1?\d?\d|(2([0-4]\d|5[0-4]))))|(((1?\d?\d|(2([0-4]\d|5[0-5])))\.){3}(1?\d?\d|(2([0-4]\d|5[0-4])))-((1?\d?\d|(2([0-4]\d|5[0-5])))\.){3}(1?\d?\d|(2([0-4]\d|5[0-4]))))$/,
valiEmail : /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/,
valiPhoneNum : /^1[34578]\d{9}$/,
valiInt : /^[1-9][0-9]*$/,
valiMAC : /[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}/,
valiEn : /[`~!@
valiCn : /[·!
valiSpace : /\s/,
}
}
valiUtils = {
userName : function(s) {
if (s.length < 8 || s.length > 15) return false
return true;
},
cardId : function(s) {
if (!MYCONSTANS.regex.valiID.exec(s)) return false
return true
},
email : function(s) {
if (!MYCONSTANS.regex.valiEmail.exec(s)) return false
return true
},
IP : function(s) {
if (!MYCONSTANS.regex.valiIP.exec(s)) return false
return true
},
File : function(s) {
if (MYCONSTANS.regex.valiEn.exec(s) || MYCONSTANS.regex.valiCn.exec(s) || MYCONSTANS.regex.valiSpace.exec(s)) return false
return true
}
}
Map.prototype.toKeyValueArr = function() {
var newArr = [];
for (var [key, val] of this.entries()) {
newArr.push({
key : key,
value : val
}) }
return newArr;
};
Map.prototype.getEntrys = function() {
return Array.from(this.entries());
};
Array.prototype.wordCount = function() {
var result = this;
var arr = [];
for (var i = 0; i < result.length;) {
var count = 0;
for (var j = i; j < result.length; j++) {
if (result[i] === result[j]) {
count++;
}
}
arr.push({
date : result[i],
count : count
})
i += count;
}
return arr;
}
//用户自定义配置
XAJAUserConfig = {}
//默认的所有配置
XAJAConfig = {
successKey : "success",
successValue : true,
unSuccessValue : false,
successValueBooleanType : true,
successMsgKey : "msg",
successTipPlugin : function(msg) {
//alert(msg + "[这是默认执行的]");
toastr.success(msg);
},
confirmPlugin : function(msg, callback) {
bootbox.confirm({
message : msg ? msg : "确定执行该操作吗?",
size : 'small',
buttons : {
confirm : {
label : '确定',
className : 'btn-success'
},
cancel : {
label : '取消',
className : 'btn-danger'
}
},
callback : function(result) {
if (result) {
callback();
}
}
});
},
//默认执行的失败回调方法
failTipPlugin : function(msg) {
bootbox.alert({
message : msg,
size : 'small',
});
},
//默认执行的错误回调方法
innormalTipPlugin : function(xhr) {
// alert("状态码:" + xhr.status + "[这是默认执行的]");
// toastr.warning("状态码:" + xhr.status);
},
//默认不成功的回调方法
unSuccessTipPlugin : function(result) {
//alert(result.msg + "[这是默认执行的]");
//sweetAlert("结果", result.msg, "error");
bootbox.alert({
message : result.msg,
size : 'small',
});
},
}
工具类
IPUtils = {
//IP转数字
ip2int: function (ip) {
var num = 0;
ip = ip.split(".");
num = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3]);
num = num >>> 0;
return num;
},
//数字转IP
int2iP: function (num) {
var str;
var tt = new Array();
tt[0] = (num >>> 24) >>> 0;
tt[1] = ((num << 8) >>> 24) >>> 0;
tt[2] = (num << 16) >>> 24;
tt[3] = (num << 24) >>> 24;
str = String(tt[0]) + "." + String(tt[1]) + "." + String(tt[2]) + "." + String(tt[3]);
return str;
},
//列出IP段内的IP
listIP: function (ip1, ip2) {
var ipInt1 = this.ip2int(ip1);
var ipInt2 = this.ip2int(ip2);
var arr = new Array();
var index = 0;
for (var i = ipInt1; i <= ipInt2; i++) {
arr[index] = this.int2iP(i);
index++;
}
return arr;
}
}
function getDisabled(obj) {
var isHas = obj.is('disabled');
// 如果有
if (isHas) {
// 返回disabled是有还是没有
return obj.attr("disabled");
} else {
// 如果没有,返回false
return false;
}
}
function isIE() { //ie?
if (!!window.ActiveXObject || "ActiveXObject" in window)
return true;
else
return false;
}
function setTimeoutInterval(callback,clear,interval,timeout){
var t = new Date().getTime();
var i = setInterval(function(){
callback();
if(new Date().getTime() - t > timeout){
clearInterval(i);
if(clear)
clear();
}
},interval);
return i;
}
var DataUtils = {};
DataUtils.obj_arrs = new Array();
DataUtils.transArr = function (arr, objs) {
this.obj_arrs = new Array();
var isJson = true;
for (var i = 0; i < arr.length; i++) {
if (isJson) {
var objStr = "{";
for (var Key in objs) {
var value = arr[i][objs[Key]];
if (!isNaN(value)) {
objStr = objStr + "\"" +
Key + "\":" + value + ",";
} else {
objStr = objStr + "\"" +
Key + "\":" + "\"" + value + "\",";
}
}
//删除最后的逗号
objStr = objStr.substring(0, objStr.length - 1);
objStr = objStr + "}";
this.obj_arrs.push(JSON.parse(objStr));
} else {
var objStr = arr[i][objs];
this.obj_arrs.push(objStr);
}
}
for (var i = 2; i < arguments.length; i++) {
this.obj_arrs.push(arguments[i])
}
return this;
}
DataUtils.toMyJson = function () {
{
return JSON.stringify(this.obj_arrs);
}
}
DataUtils.toMyObj = function () {
{
return this.obj_arrs;
}
}
DownloadUtils = {
download: function (filename, content) {
var a = document.createElement('a');
var blob = new Blob([content], {
'type': 'text/plain;charset=utf-8'
});
var obj_url = window.URL.createObjectURL(blob);
a.href = obj_url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(obj_url);
},
saveFile: function (data, filename) {
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = data;
save_link.download = filename;
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
save_link.dispatchEvent(event);
}
}
StringUtils = {
isAllSameInArr: function (arr, key) {
var first = arr[0][key];
for (var i = 0; i < arr.length; i++) {
var value = arr[i][key];
if (value != first) {
return false;
}
}
return true;
},
spiltByTag: function (arr, tag) {
var result = "";
for (var i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
result = result + arr[i];
} else {
result = result + arr[i] + tag;
}
}
return result;
},
// 链表转数组
ListToArr: function (list) {
// 横坐标数组
var arr = new Array(list.Size());
for (var i = 0; i < list.Size(); i++) {
arr[i] = list.GetData(i);
}
return arr;
},
};
RanDomUtils = {
getRandom: function (min, max) {
var r = Math.random() * (max - min);
var re = Math.round(r + min);
re = Math.max(Math.min(re, max), min);
return re;
}
};
var aop = {
exec: function (filter, func) {
if (filter != null) {
if (eval(filter)) {
for (var i = 0; i < func.length; i++) {
eval(func[i]);
}
}
} else {
for (var i = 0; i < func.length; i++) {
eval(func[i]);
}
}
}
};
AjaxUtils = {
doError: function (error_f, XMLHttpRequest) {
if (XMLHttpRequest.status == "403") {
// console.info($(parent.document).find("meta[name='keywords']").attr("content"));
if (error_f) {
error_f("你没有操作权限");
} else {
if ($("meta[name='keywords']").attr("content") == "HOME") {
bootbox.alert("你没有操作权限");
} else {
parent.bootbox.alert("你没有操作权限");
}
}
} else if (XMLHttpRequest.status == "0") {
if (error_f) {
bootbox.alert({
size: 'small',
message: '网络错误',
callback: function () {
error_f();
}
});
}
} else if (XMLHttpRequest.status == "400") {
bootbox.alert("Bad Resq");
}
},
sendForm: function (formId, success_f, fail_f, error_f) {
var options = {
success: function (result) {
if (result.success) {
if (success_f) {
success_f(result);
}
} else {
if (fail_f) {
fail_f(result);
}
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
AjaxUtils.doError(error_f, XMLHttpRequest);
}
};
$("#" + formId).ajaxForm(options);
},
sendFormData: function (url, data, success_f, fail, error_f) {
$.ajax({
url: url,
type: 'POST',
data: data,
contentType: false,
processData: false,
cache: false,
success: function (result) {
if (result.success) {
if (success_f) {
success_f(result);
} else {
bootbox.alert({
message: result.msg,
size: 'small',
});
}
} else {
if (fail) {
fail(result);
}
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
AjaxUtils.doError(error_f, XMLHttpRequest);
},
});
},
sendResq: function (url, type, data, success_f, fail, error_f) {
$.ajax({
url: url,
type: type,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.success) {
if (success_f) {
success_f(result);
}
} else {
if (fail) {
fail(result);
}
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
AjaxUtils.doError(error_f, XMLHttpRequest);
},
});
},
}
//Constructor.
var Interface = function (name, methods) {
if (arguments.length != 2) {
throw new Error("Interface constructor called with " + arguments.length + "arguments, but expected exactly 2.");
}
this.name = name;
this.methods = [];
for (var i = 0, len = methods.length; i < len; i++) {
if (typeof methods[i] !== 'string') {
throw new Error("Interface constructor expects method names to be " + "passed in as a string.");
}
this.methods.push(methods[i]);
}
};
//Static class method.
Interface.ensureImplements = function (object) {
if (arguments.length < 2) {
throw new Error("Function Interface.ensureImplements called with " + arguments.length + "arguments, but expected at least 2.");
}
for (var i = 1, len = arguments.length; i < len; i++) {
var interface1 = arguments[i];
if (interface1.constructor !== Interface) {
throw new Error("Function Interface.ensureImplements expects arguments" + "two and above to be instances of Interface.");
}
for (var j = 0, methodsLen = interface1.methods.length; j < methodsLen; j++) {
var method = interface1.methods[j];
if (!object[method] || typeof object[method] !== 'function') {
throw new Error("Function Interface.ensureImplements: object " + "does not implement the " + interface1.name + " interface. Method " + method + " was not found.");
}
}
}
};
/**
* @version 1.0 用于实现页面 Map 对象,Key只能是String,对象随意
*/
var Node = function (newData) {
this.next = null;
this.data = null;
this.Init = function () {
this.data = newData;
};
this.Init();
};
var MYCONSTANS = {
regex: {
valiIP: /^((1?\d?\d|(2([0-4]\d|5[0-5])))\.){3}(1?\d?\d|(2([0-4]\d|5[0-4])))$/,
valiIPRange: /^((1?\d?\d|(2([0-4]\d|5[0-5])))\.){3}(1?\d?\d|(2([0-4]\d|5[0-4])))-((1?\d?\d|(2([0-4]\d|5[0-5])))\.){3}(1?\d?\d|(2([0-4]\d|5[0-4])))$/,
valiEmail: /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/,
valiPhoneNum: /^1[34578]\d{9}$/,
valiInt: /^[1-9][0-9]*$/,
valiMAC: /[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}/,
valiEn: /[`~!@
valiCn: /[·!
valiSpace: /\s/,
}
}
valiUtils = {
userName: function (s) {
if (s.length < 8 || s.length > 15) return false
return true;
},
cardId: function (s) {
if (!MYCONSTANS.regex.valiID.exec(s)) return false
return true
},
email: function (s) {
if (!MYCONSTANS.regex.valiEmail.exec(s)) return false
return true
},
IP: function (s) {
if (!MYCONSTANS.regex.valiIP.exec(s)) return false
return true
},
File: function (s) {
if (MYCONSTANS.regex.valiEn.exec(s) || MYCONSTANS.regex.valiCn.exec(s) || MYCONSTANS.regex.valiSpace.exec(s)) return false
return true
}
}