常用JavaScript代码库(又名:WFang.js)
Posted 亦心晗
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常用JavaScript代码库(又名:WFang.js)相关的知识,希望对你有一定的参考价值。
1.根据公司项目封装ajax请求,结合layer框架一起使用
/*提取接口公共部分*/ var ApiConf = { server:"http://localhost:8080/Battery/", }; /** * 调用接口方法 * api:接口 * callback:回调函数 * info:参数 * type:请求方式 */ function WFang (api, callback, info , type){ //加载动画 layer.load(); //参数 var data = info; var contentType = ‘application/x-www-form-urlencoded; charset=UTF-8‘; if(type == ‘post‘){ contentType = ‘application/json‘; }else if(type == ‘get‘){ contentType = ‘application/x-www-form-urlencoded; charset=UTF-8‘; } if (typeof(data) === ‘undefined‘) { layer.msg("提交的参数缺失", "出现错误了哦:"); return; } window.ajax_request = $.ajax({ type: type, dataType: ‘json‘, async: ‘false‘, xhrFields: { withCredentials: true }, crossDomain: true, url: ApiConf.server+api, data: info, success: function(data) { //停止加载动画 layer.closeAll(‘loading‘); if (data.status) { callback(data); } else if (data.status==false){ callback(data); } }, error: function(XMLHttpRequest) { layer.msg(‘服务器遇到了问题哦,请联系客服~~~‘); }, complete: function(XMLHttpRequest, textStatus){ window.ajax_request = null; }, contentType:contentType //contentType:‘application/x-www-form-urlencoded; charset=UTF-8‘ }); } /** * 接口方法使用示例 * 登录(包含cookie存储) */ function user_login(userName,password){ WFang ("user/userLogin",function(arr){ var yCode = $(‘.yCode‘).val().trim().toUpperCase(); var code = $(‘.yzm‘).html(); if(arr.status == false){ layer.msg(arr.message); }else{ if ($("#remid").is(‘:checked‘) == true) { var username = $(‘#uname‘).val().trim(); var password = $(‘#upwd‘).val().trim(); $.cookie("rmbUser", "true", { expires: 30 }); //存储一个带30天期限的cookie $.cookie("username", userName, { expires: 30 }); $.cookie("password", password, { expires: 30 }); } else { $.cookie("rmbUser", "false", { expire: -1 }); $.cookie("username", "", { expires: -1 }); $.cookie("password", "", { expires: -1 }); } var jumpto ="index.html"; window.location.replace(jumpto); window.sessionStorage.setItem(UrlConf.tk_rolename,arr.data.realName.trim()); window.sessionStorage.setItem(UrlConf.tk_uid,arr.data.userId.trim()); window.sessionStorage.setItem(UrlConf.tk_uPhone,arr.data.phone.trim()); } },{userName:userName,password:password} ) }; /** * 接口方法使用示例 * 注销 */ function logout() { WFang ("user/loginOut",function(arr){ if(arr.status){ // TODO clear all cookies $.cookie("rmbUser", "false", { expire: -1 }); $.cookie("username", "", { expires: -1 }); $.cookie("password", "", { expires: -1 }); layer.msg("退出登录"); setTimeout("window.location.href=‘login.html‘",1000); } },{},‘get‘); }
2.生成验证码
/** * 生成验证码方法 * 可用于登录页面生成验证码 */ function createCode(){ var code = ""; var codeLength = 4;//验证码的长度 var random = [‘A‘,‘B‘,‘C‘,‘D‘,‘E‘,‘F‘,‘G‘,‘H‘,‘I‘,‘J‘,‘K‘,‘L‘,‘M‘,‘N‘,‘O‘,‘P‘,‘Q‘,‘R‘, ‘S‘,‘T‘,‘U‘,‘V‘,‘W‘,‘X‘,‘Y‘,‘Z‘];//随机数 for( var i = 0; i < codeLength; i++ ) {//循环操作 var index = Math.floor(Math.random()*26);//取得随机数的索引(0~35) code += random[index];//根据索引取得随机数加到code上 } $(‘.yzm‘).html(code);//把code值赋给验证码 }
3.时间戳转日起对象
/** * 时间戳转换成日期对象 */ function getLocalTime(nS) { return new Date(parseInt(nS)).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " "); }
4.截取url参数
/** * 截取url参数 * 用于截取页面之间传递的参数 */ function getUrl(){ var search = location.search; var params = {}; if(params != ‘‘){ var ps = search.slice(1).split(‘&‘); for(var i = 0;i < ps.length;i++){ var arr = ps[i].split(‘=‘); params[arr[0]] = arr[1]; } } return params; }
5.去除前后空格
/** * 去除前后空格 * 前端传给后台的参数需去除前后空格 */ function Trim(str){ return str.replace(/(^\s*)|(\s*$)/g, ""); }
6.获得字符串长度
/** * 获得字符串长度 * 可用于表单输入长度验证 */ function getLen(str){ var len = 0; for(var i = 0;i < str.length;i++){ if(str.charCodeAt(i)>255){//charCodeAt() 方法可返回指定位置的字符的 Unicode 编码 len += 2; }else{ len++; } } return len; }
7.图片压缩上传
/** * 图片压缩上传 * 上传前用js对图片压缩,把利用canvas生成的base64字符串,传入后台, * (无所谓ajax或者form,同时也可以解决图片无刷新上传), * 在Java后台将获取到的base64字符串输出为图片,即可。 */ function caseUploadFile(files, callback) { var fd = new FormData(); fd.append("fileCommon.fileSource", "lists"); fd.append("fileCommon.fileType", "JPG,BMP,GIF,TIF,PNG"); for (var i = 0; i < files.length; i++) { var file = files[i]; var URL = window.URL || window.webkitURL; var blob = URL.createObjectURL(file); //画图 var img = new Image(); img.src = blob; img.onload = function() { var that = this; //生成比例 var w = that.width, h = that.height, scale = w / h; w = 640 || w; h = w / scale; //生成canvas var canvas = document.createElement(‘canvas‘); var ctx = canvas.getContext(‘2d‘); $(canvas).attr({ width: w, height: h }); ctx.drawImage(that, 0, 0, w, h); /** * 生成base64 * 兼容修复移动设备需要引入mobileBUGFix.js */ var base64 = canvas.toDataURL(‘image/jpeg‘, 0.8 || 0.8); // 修复ios if (navigator.userAgent.match(/iphone/i)) { var mpImg = new MegaPixImage(img); mpImg.render(canvas, { maxWidth: w, maxHeight: h, quality: obj.quality || 0.8 }); base64 = canvas.toDataURL(‘image/jpeg‘, 0.8 || 0.8); } // 修复android if (navigator.userAgent.match(/Android/i)) { var encoder = new JPEGEncoder(); base64 = encoder.encode(ctx.getImageData(0, 0, w, h), 0.8 * 100 || 80); } imgData = base64; fd.append("files.filess", files[0]); }; } var xhr = new XMLHttpRequest(); if (typeof(callback) === ‘function‘) { xhr.addEventListener("load", function (evt) { Toast(null, null, null, 3); callback(evt); }, false); } xhr.addEventListener("error", uploadFailed, false); xhr.addEventListener("abort", uploadCanceled, false); xhr.open("POST", ApiConf.server + ApiConf.case_upload_img); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(fd); }
8.文件上传
/*文件上传(待续)*/ function uploadFile(){ var that=this;//保存当前this var file = that.files[0]; var fd = new FormData(); fd.append("file", file); fd.append("fileDesc", "test"); layer.load(0); $.ajax({ async: true, url: ApiConf+‘Resource/ResourceAdd‘, type: "POST", dataType: ‘json‘, data: fd, contentType: false, beforeSend: function (xhr) { xhr.setRequestHeader("authorization", token); }, xhr: function() { myXhr = $.ajaxSettings.xhr(); return myXhr; }, success:function(arr) { //头像id that.setAttribute(‘name‘,arr.data[0].resourceid); layer.msg(‘文件上传成功‘,{icon: 1}); layer.closeAll(‘loading‘); }, error:function() { layer.msg("上传失败"); }, cache:false, processData:false }); }
9.全选/全不选
/* * 全选/全不选 */ function selectAll(objSelect) { if (objSelect.checked == true) { $("input[name=‘chkId‘]").attr("checked", true); $("input[name=‘chkAll‘]").attr("checked", true); } else if (objSelect.checked == false) { $("input[name=‘chkId‘]").attr("checked", false); $("input[name=‘chkAll‘]").attr("checked", false); } }
10.判断两个日期大小
/* * 判断两个日期大小 * 得到日期值并转化成日期格式,replace(/\-/g, "\/")是根据验证表达式把日期转化成长日期格式,这样再进行判断就好判断了 */ function ValidateDate() { var beginDate = $("#t_datestart").val(); var endDate = $("#t_dateend").val(); if (beginDate.length > 0 && endDate.length>0) { var sDate = new Date(beginDate.replace(/\-/g, "\/")); var eDate= new Date(endDate.replace(/\-/g, "\/")); if (sDate > eDate) { alert(‘开始日期要小于结束日期‘); return false; } } }
11.回车提交
/* * 回车提交 */ $("id").onkeypress = function (event) { event = (event) ? event : ((window.event) ? window.event : "") keyCode = event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode); if (keyCode == 13) { $("SubmitLogin").onclick(); } }
12.获得当前时间
/* * 获得当前时间 */ function checkTime(i){ if(i<10){ i="0"+i; } return i; } function showTime(){ var date=$("#spanData"); var mydate=new Date; var y=mydate.getFullYear(); var m=mydate.getMonth()+1; var d=mydate.getDate(); var w=mydate.getDay(); var h=mydate.getHours(); var f=mydate.getMinutes(); var s=mydate.getSeconds(); f=checkTime(f); s=checkTime(s); var week=""; var week=[‘星期日‘,‘星期一‘,‘星期二‘,‘星期三 ‘,‘星期四‘,‘星期五‘,‘星期六‘]; date.html(y+"年"+m+"月"+d+"日"+" "+week[w]+" "+h+":"+f+":"+s); setTimeout(showTime,1000); }
以上是关于常用JavaScript代码库(又名:WFang.js)的主要内容,如果未能解决你的问题,请参考以下文章