项目中经常使用的JS方法汇总,非常有用
// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
getPageRegion = function (pageidx, pagecount, buttonnum) {
buttonnum = buttonnum || 5;
var halfbuttonnum = Math.floor(buttonnum / 2);
var start = pageidx - halfbuttonnum > 0 ? pageidx - halfbuttonnum : 0;
var end = start + buttonnum > pagecount ? pagecount : start + buttonnum;
start = end - buttonnum < 0 ? 0 : end - buttonnum;
return { start: start, end: end, pageidx: pageidx, pagecount: pagecount, buttonnum: buttonnum };
}
parseString = function (obj) {
switch (typeof (obj)) {
case 'string':
//return '"' + obj.replace(/(["file://])/g, '\\$1') + '"';
return '"' + obj + '"';
case 'array':
return '[' + obj.map(parseString).join(',') + ']';
case 'object':
if (obj instanceof Array) {
var strArr = [];
var len = obj.length;
for (var i = 0; i < len; i++) {
strArr.push(parseString(obj[i]));
}
return '[' + strArr.join(',') + ']';
} else if (obj == null) {
return 'null';
} else {
var string = [];
for (var property in obj) string.push(parseString(property) + ':' + parseString(obj[property]));
return '{' + string.join(',') + '}';
}
case 'number':
return obj;
default:
return obj;
}
}
ajax = function (uri, data, callback) {
$.ajax({
type: "post",
cache: false,
url: uri,
data: data,
dataType: "json",
contentType: "application/json",
success: callback,
error: function (res) { alert(res) }
});
}
getQueryString = function (name) {
var queryStrings = window.location.search.split('&');
for (var i = 0; i < queryStrings.length; i++) {
if (queryStrings[i].indexOf(name + "=") != -1)
return queryStrings[i].substr(queryStrings[i].indexOf(name + "=") + name.length + 1, queryStrings[i].length);
}
return "";
}
logout = function () {
ajax("/WebServices/WSLogin.asmx/Logout", {}, function (r) { location.href = "/Login.aspx" });
}
function encrypt(str, pwd) {
if(pwd == null || pwd.length <= 0) {
alert("Please enter a password with which to encrypt the message.");
return null;
}
var prand = "";
for(var i=0; i<pwd.length; i++) {
prand += pwd.charCodeAt(i).toString();
}
var sPos = Math.floor(prand.length / 5);
var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));
var incr = Math.ceil(pwd.length / 2);
var modu = Math.pow(2, 31) - 1;
if(mult < 2) {
alert("Algorithm cannot find a suitable hash. Please choose a different password. \nPossible considerations are to choose a more complex or longer password.");
return null;
}
var salt = Math.round(Math.random() * 1000000000) % 100000000;
prand += salt;
while(prand.length > 10) {
prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
}
prand = (mult * prand + incr) % modu;
var enc_chr = "";
var enc_str = "";
for(var i=0; i<str.length; i++) {
enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
if(enc_chr < 16) {
enc_str += "0" + enc_chr.toString(16);
} else enc_str += enc_chr.toString(16);
prand = (mult * prand + incr) % modu;
}
salt = salt.toString(16);
while(salt.length < 8)salt = "0" + salt;
enc_str += salt;
return enc_str;
}
function decrypt(str, pwd) {
if(str == null || str.length < 8) {
alert("A salt value could not be extracted from the encrypted message because it's length is too short. The message cannot be decrypted.");
return;
}
if(pwd == null || pwd.length <= 0) {
alert("Please enter a password with which to decrypt the message.");
return;
}
var prand = "";
for(var i=0; i<pwd.length; i++) {
prand += pwd.charCodeAt(i).toString();
}
var sPos = Math.floor(prand.length / 5);
var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));
var incr = Math.round(pwd.length / 2);
var modu = Math.pow(2, 31) - 1;
var salt = parseInt(str.substring(str.length - 8, str.length), 16);
str = str.substring(0, str.length - 8);
prand += salt;
while(prand.length > 10) {
prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
}
prand = (mult * prand + incr) % modu;
var enc_chr = "";
var enc_str = "";
for(var i=0; i<str.length; i+=2) {
enc_chr = parseInt(parseInt(str.substring(i, i+2), 16) ^ Math.floor((prand / modu) * 255));
enc_str += String.fromCharCode(enc_chr);
prand = (mult * prand + incr) % modu;
}
return enc_str;
}
(function ($) {
function raw(s) {
return s;
}
function decoded(s) {
return window.decode(s.replace(/\+/g, ' '));
}
function encode(s) {
return window.encode(s);
}
function converted(s) {
if (s.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
try {
return config.json ? JSON.parse(s) : s;
} catch (er) { }
}
var config = $.cookie = function (key, value, options) {
if (value !== undefined) {
options = $.extend({}, config.defaults, options);
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
value = config.json ? JSON.stringify(value) : String(value);
return (document.cookie = [
options.raw ? key : encode(key),
'=',
options.raw ? value : encode(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// read
var decode = config.raw ? raw : decoded;
var cookies = document.cookie.split('; ');
var result = key ? undefined : {};
for (var i = 0, l = cookies.length; i < l; i++) {
var parts = cookies[i].split('=');
var name = decode(parts.shift());
var cookie = decode(parts.join('='));
if (key && key === name) {
result = converted(cookie);
break;
}
if (!key) {
result[name] = converted(cookie);
}
}
return result;
};
$.removeCookie = function (key, options) {
if ($.cookie(key) !== undefined) {
$.cookie(key, '', $.extend(options, { expires: -1 }));
return true;
}
return false;
};
config.defaults = {};
})(jQuery);
(function (_) {
var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64DecodeChars = new Array(
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
_.encode = function (str) {
var out, i, len;
var c1, c2, c3;
len = str.length;
i = 0;
out = "";
while (i < len) {
c1 = str.charCodeAt(i++) & 0xff;
if (i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt((c1 & 0x3) << 4);
out += "==";
break;
}
c2 = str.charCodeAt(i++);
if (i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt((c2 & 0xF) << 2);
out += "=";
break;
}
c3 = str.charCodeAt(i++);
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
out += base64EncodeChars.charAt(c3 & 0x3F);
}
return out;
}
_.decode = function (str) {
var c1, c2, c3, c4;
var i, len, out;
len = str.length;
i = 0;
out = "";
while (i < len) {
do {
c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
} while (i < len && c1 == -1);
if (c1 == -1)
break;
do {
c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
} while (i < len && c2 == -1);
if (c2 == -1)
break;
out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
do {
c3 = str.charCodeAt(i++) & 0xff;
if (c3 == 61)
return out;
c3 = base64DecodeChars[c3];
} while (i < len && c3 == -1);
if (c3 == -1)
break;
out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
do {
c4 = str.charCodeAt(i++) & 0xff;
if (c4 == 61)
return out;
c4 = base64DecodeChars[c4];
} while (i < len && c4 == -1);
if (c4 == -1)
break;
out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
}
return out;
}
})(window);
以上内容可以直接拷贝到一个.js文件中,作为外部js文件使用,前提是必须先引用jquery.js文件,
以上代码已包含jquery的cookie的实现代码,如需要用jquery方式来保存并使用cookie,示例如下:
//前台生成的cookie,如果需要后台使用,则必须加上
path: "/", raw: true 这2个选项,如:
$.cookie("user_mobile", $("#loginMobile").val(), { expires: 1, path: "/", raw: true });
后天获取时,代码如下:
if (Request.Cookies["user_mobile"] != null)
{
Mobile = Request.Cookies["user_mobile"].Value;
}
前台生成cookie,前台获取使用时,不能设置 raw: true, 代码如下:
$.cookie("user_mobile_js", $("#loginMobile").val(), { expires: 1, path: "/" });
前台获取Cookie时代码如下:
mobile = $.cookie("user_mobile_js");
删除某个cookie时,代码如下:
$.cookie("user_mobile_js", null, { expires: -1, path: "/" });
$.cookie("user_mobile", null, { expires: -1, path: "/" });
调用ajax异步方法时:
ajax("/WebService/WebService1.asmx/LoginIn", parseString({ Mobile: mobile, Password: pwd }), function(data){...});
项目中经常使用的JS方法汇总,非常有用的更多相关文章
- SuperDiamond在JAVA项目中的三种应用方法实践总结
SuperDiamond在JAVA项目中的三种应用方法实践总结 1.直接读取如下: @Test public static void test_simple(){ PropertiesConfigur ...
- asp.net中导出excel数据的方法汇总
1.由dataset生成 代码如下 复制代码 public void CreateExcel(DataSet ds,string typeid,string FileName) { Htt ...
- 转:Qt项目中遇到的一些小问题汇总
链接:http://blog.csdn.net/yangyunfeizj/article/details/7082001 作者:GoatYangYang 公司让负责qt界面开发,但是接触qt又不 ...
- swift项目中使用OC/C的方法
假如有个OC类OCViewController : UIViewController类里有两个方法 //swift调用oc或c的混编是比较常用的,反过来的调用很少.这里只写了swift调用oc和c的方 ...
- web项目中获取各种路径的方法
~Apple web项目中各种路径的获取 1.可以在servlet的init方法里 String path = getServletContext().getRealPath("/&qu ...
- angular6项目中使用echarts图表的方法(有一个坑,引用报错)
1.安装相关依赖(采用的webpack) npm install ecahrts --save npm install ngx-echarts --save 2.angular.json 配置echa ...
- php中class类文件引入方法汇总
在项目中 总是会用到类文件引入的操作,在此简单总结下: 方法一: 使用 include,require,include_once,require_once. 其中:*_once once意为曾经 ...
- 标签中的onclick调用js方法传递多个参数的解决方案
1.JS方法 <script type="text/javascript"> funcation cc(parameter1,parameter2,parameter3 ...
- 拼接的html的onclick事件中无法传递对象给js方法的处理办法
如下: 拼接的html: " onclick=\"valDocName2('"+JSON.stringify(doc).replace(new RegExp(" ...
随机推荐
- Leetcode:minimum_depth_of_binary_tree解决问题的方法
一. 称号 并寻求最深的二元相似.给定的二进制树.求其最小深度. 最小深度是沿从根节点,到叶节点最短的路径. 二. 分析 当我看到这个题目时.我直接将最深二叉树的代码略微改了下,把ma ...
- 截图工具 Snagit
相对于其他截图工具方面,Snagit 一个主要特点是: 滚动截图. 另:同样基于手工绘制的形状截图, 有可能截取文本(测试只 windows在窗口内的目录 要么 文件名 实用). 不管是 web页,是 ...
- CF 148D. Bag of mice (可能性DP)
D. Bag of mice time limit per test 2 seconds memory limit per test 256 megabytes input standard inpu ...
- 【SQL】Oracle的PL/SQL语法及其拓展数据类型总结
PL/SQL语法 PL/SQL程序由三部分组成,声明部分.执行部分.异常处理部分. 模板: DECLARE /*变量声明*/ BEGIN /*程序主体*/ EXCEPTION /*异常处理部分*/ E ...
- POJ2029——Get Many Persimmon Trees
Get Many Persimmon Trees Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 3656 Accepte ...
- 1号店Interview小结
三大范式: 为了建立冗余较小.结构合理的数据库,设计数据库时必须遵循一定的规则.在关系型数据库中这种规则就称为范式.范式是符合某一种设计要求的总结.要想设计一个结构合理的关系型数据库,必须满足一定的范 ...
- 《Tips for Optimizing C/C++ Code》译文
前不久在微博上看到一篇非常好的短文讲怎样对C/C++进行性能优化,尽管其面向的领域是图形学中的光线跟踪,可是还是具有普遍的意义,将其翻译成中文,希望对大家写高质量代码有帮助. 1. 牢记阿姆达 ...
- 移动端 transition动画函数的封装(仿Zepto)以及 requestAnimationFrame动画函数封装(仿jQuery)
移动端 css3 transition 动画 ,requestAnimationFrame 动画 对于性能的要求,h5优先考虑: 移动端 单页有时候 制作只用到简单的css3动画即可,我们封装一下, ...
- 2014年百度之星程序设计大赛 - 资格赛 1002 Disk Schedule(双调欧几里得旅行商问题)
Problem Description 有非常多从磁盘读取数据的需求,包含顺序读取.随机读取.为了提高效率,须要人为安排磁盘读取.然而,在现实中,这样的做法非常复杂.我们考虑一个相对简单的场景.磁盘有 ...
- Team Foundation Server 2015使用教程--tfs用户账号切换