ExtJS 中用js 操作cookie的方法
最后更新于:2022-04-01 12:00:52
cookie.js文件
~~~
偶尔发现ExtJS中有操作cookie的js方法,拿来给大家分享下。
var Cookies = {};
Cookies.set = function(name, value){
var argv = arguments;
var argc = arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : '/';
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
};
Cookies.get = function(name){
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
var j = 0;
while(i < clen){
j = i + alen;
if (document.cookie.substring(i, j) == arg)
return Cookies.getCookieVal(j);
i = document.cookie.indexOf(" ", i) + 1;
if(i == 0)
break;
}
return null;
};
Cookies.clear = function(name) {
if(Cookies.get(name)){
document.cookie = name + "=" +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
};
Cookies.getCookieVal = function(offset){
var endstr = document.cookie.indexOf(";", offset);
if(endstr == -1){
endstr = document.cookie.length;
}
return unescape(document.cookie.substring(offset, endstr));
};
~~~
示例:
~~~
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>OperateCookie.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="cookie.js"></script>
<script type="text/javascript">
function set() {
Cookies.set("name", "tom");
Cookies.set("sex", "男");
}
function get() {
alert(Cookies.get("name"));
alert(Cookies.get("sex"));
}
function clear(s) {
Cookies.clear(s);
}
</script>
</head>
<body>
<input type="button" value=" set " onclick="set()"/>
<input type="button" value=" get " onclick="get()"/>
<input type="button" value=" clear sex " onclick="clear('sex')"/>
<input type="button" value=" clear name " onclick="clear('name')"/>
</body>
</html>
~~~
可以参考:[http://blog.csdn.net/IBM_hoojo/archive/2010/07/02/5709282.aspx](http://blog.csdn.net/IBM_hoojo/archive/2010/07/02/5709282.aspx)