`
icrwen
  • 浏览: 268189 次
  • 性别: Icon_minigender_2
  • 来自: 济南
社区版块
存档分类
最新评论

javascript cookie的删除 保存 读取

    博客分类:
  • JS
阅读更多

you really don't need much knowledge to use this script, it's pretty much plug and play, but we'll explain it's main part and how to use them anyway. If you have specific questions, please post them in our Javascript Forum and we will answer them there.

Set Cookie Javascript Function

You need to put the name and values in quotes when you call the function, like this:
Set_Cookie( 'mycookie', 'visited 9 times', 30, '/', '', '' );. Don't forget to put in empty quotes for the unused parameters or you'll get an error when you run the code. This makes the cookie named 'mycookie', with the value of 'visited 9 times', and with a life of 30 days, and the cookie is set to your root folder.

The Set_Cookie values for 'domain' and 'secure' are not utilized. Use 'domain' on the Javascript cookie if you are using it on a subdomain, like widgets.yoursite.com, where the cookie is set on the widgets subdomain, but you need it to be accessible over the whole yoursite.com domain.

It's good practice to not assume the path to the site root will be set the way you want it by default, so do this manually as a rule, '/'. If no value is set for expires, it will only last as long as the current session of the visitor, and will be automatically deleted when they close their browser.

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}
			

This will set the cookie. It's the most complicated part, but actually for most purposes all you need to set are the first 4 parameters, name, value, expires, and path. If you want the cookie available only in one folder, you will need to add '/folder_name/' as a path variable, that tells the script to set the cookie for the just that path, not for the whole domain.

As a good general rule, set the path to '/', the root of your website. Generally 'domain' and 'secure' are not something you will be needing to use unless you set the cookie on a subdomain, in which case you may want to set the domain to your primary domain if you want it to be accessible from the main domain, or other subdomains.

Get Cookie Javascript Function
// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
				

Please note that the above version fixes some fairly serious issues with the old version, here listed below for comparison. The original utterly fails to handle cases where cookie names are substrings of other cookies, say like: site_main, site_main2 and so on. Thanks to ThoughtfulCoder for point this problem out. What's amazing to contemplate that this original code has been up for years without anyone noticing that weakness.

// this function gets the cookie, if it exists
// don't use this, it's weak and does not handle some cases
// correctly, this is just to maintain legacy information
function Get_Cookie( name ) {

var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) &&
( name != document.cookie.substring( 0, name.length ) ) )
{
return null;
}
if ( start == -1 ) return null;
var end = document.cookie.indexOf( ";", len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
}
			

This will retrieve the cookie by name, if the cookie does not exist, it will return false, so you can do things like if ( Get_Cookie( 'your_cookie' ) ) do something.

Delete Cookie Javascript Function
// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
			

Here all you need to do is put in: Delete_Cookie('cookie name', '/', '') and the cookie will be deleted. Remember to match the cookie name, path, and domain to what you have it in Set_Cookie exactly, or you may get some very hard to diagnose errors.

WARNING: Do not assume the Cookie has actually been deleted during that session, both Opera and IE have in some of their browser versions maintained the cookie until you restart your browser even if you have deleted it in the script. If script functionality depends on the delete action having happened, make sure you do another Get_Cookie test on the deleted cookie to make sure it's actually deleted.

Sample Page Code for Javascript Cookies
<script type="text/javascript">
// remember, these are the possible parameters for Set_Cookie:
// name, value, expires, path, domain, secure
Set_Cookie( 'test', 'it works', '', '/', '', '' );
if ( Get_Cookie( 'test' ) ) alert( Get_Cookie('test'));
// and these are the parameters for Delete_Cookie:
// name, path, domain
// make sure you use the same parameters in Set and Delete Cookie.
Delete_Cookie('test', '/', '');
( Get_Cookie( 'test' ) ) ? alert( Get_Cookie('test')) :
alert( 'it is gone');
</script>
			

If you run this, what will happen is that you will get two alerts, the first one will have the content you set with Set_Cookie, the second will say 'it is gone' since you have now deleted the cookie. That's about it.

 

分享到:
评论

相关推荐

    Javascript Cookie操作类的封装

    接下来,我们来创建一个名为`CookieManager`的JavaScript类,用于封装Cookie的操作。这个类需要包含以下方法: 1. **setCookie**:用于设置Cookie。需要传入键(key)、值(value)以及可选的过期时间(days)和...

    javascript cookie 操作框架 XCookie

    总结一下,XCookie是一个实用的JavaScript库,用于简化浏览器cookie的管理工作,它提供了一组易于理解和使用的API,涵盖了创建、读取、更新和删除cookie的各种操作。了解和掌握这个框架将有助于提高前端开发的效率,...

    CookiesjsJavaScript客户端的Cookie操作库

    "CookiejsJavaScript客户端的Cookie操作库" 指的是一种JavaScript库,专门用于在客户端(即用户浏览器)进行Cookie的操作。Cookiejs是这个库的名称,它提供了一组简单易用的API,帮助开发者方便地管理用户的Cookie。...

    jquery 设置cookie、删除cookie、获取cookie

    在前端开发中,通过 JavaScript 操作 Cookie 是一种常见的需求,尤其是为了实现用户状态的持久化存储或网站配置的保存等场景。jQuery 提供了一个非常方便的方式来处理这些操作,本文将详细介绍如何利用 jQuery 和其...

    jquery.cookie.js 以及用法 cookie读取与存储

    总结,`jquery.cookie.js`简化了JavaScript对Cookie的操作,使得在Web应用中管理用户数据变得更加便捷。然而,随着Web Storage(localStorage和sessionStorage)以及IndexedDB等现代存储技术的出现,对于大量数据或...

    javascript 中Cookie读、写与删除操作.docx

    本文将详细介绍如何在JavaScript中进行Cookie的读取、写入及删除操作,并探讨一些高级主题如跨域问题。 #### Cookie的基本概念 Cookie是一种小型文本文件,由服务器发送给客户端浏览器,浏览器会将Cookie保存起来...

    JS操作Cookies包括(读取添加与删除)

    在JavaScript中读取cookie的值,需要理解document.cookie对象返回的是一个字符串,它包含了当前域名下所有的cookie信息。读取特定cookie的值需要通过字符串分割的方式来实现。例如,如果要读取名称为objName的cookie...

    使用JavaScript实现Cookie的增删改查操作

    JavaScript作为浏览器端的主要脚本语言,提供了操作Cookie的功能。本文将详细介绍如何使用JavaScript实现Cookie的增删改查操作。 首先,理解Cookie的基本概念是必要的。Cookie由服务器端设置,并发送到用户的浏览器...

    用JS设置、读取、删除cookie

    ### 使用JavaScript进行Cookie的操作 在Web开发中,Cookie是一种常用的技术,用于存储用户的信息以便后续访问时使用。本文将详细介绍如何使用JavaScript来设置、读取和删除Cookie。 #### Cookie简介 Cookie是由...

    javascript实现cookie功能

    在这个Java工程中,尽管主要编程语言是Java,但JavaScript用于前端页面与用户的交互,包括创建、读取和删除Cookie。 首先,我们需要理解Cookie的基本概念。一个Cookie由名称、值、过期时间、路径和域等属性组成。...

    javascript.cookie

    JavaScript Cookie是Web开发中一种常见的数据存储方式,它允许在用户浏览器端存储少量的数据,这些数据可以在用户下次访问同一网站时被读取。Cookie最初由Netscape Navigator浏览器引入,现在已经成为HTTP协议的一...

    jquery cookie实现保存密码

    jQuery库负责简化JavaScript操作,而jQuery Cookie插件则提供了方便的API来处理Cookie的创建、读取和删除。 1. 引入依赖: 确保在HTML文件中包含了jQuery库和jQuery Cookie插件的链接。你可以通过CDN(内容分发网络...

    通过js来设置cookie和读取cookie,实现登陆时记住密码的功能

    读取cookie则相对简单,因为`document.cookie`返回的是所有cookie的字符串,需要解析这个字符串来获取特定的键值对: 1. 分割`document.cookie`得到单个cookie字符串数组,每个字符串以分号`;`分隔。 2. 遍历数组,...

    javascript 文本框下拉提示与cookie应用实例

    JavaScript操作Cookie的方法通常包括: 1. 设置Cookie:`document.cookie = "name=value; expires=date; path=path; domain=domain; secure";` 2. 读取Cookie:通过`document.cookie`字符串分割获取特定名称的Cookie...

    cookie应用(javascript)

    2. `getCookie(name)`: 用于读取指定名称的Cookie的值。 3. `deleteCookie(name)`: 用于删除指定名称的Cookie。 HTML文件可能是用来展示如何在实际页面中调用这些JavaScript函数的。通常,你可以通过`&lt;script&gt;`标签...

    js做的cookie记忆功能

    在这个场景中,我们讨论的是如何使用JavaScript实现一种基于cookie的记忆功能,以便在用户使用AJAX提交表单后,能够保存并恢复他们的输入,避免重复录入。这在网页应用中非常常见,比如搜索引擎的历史记录功能,就像...

    javascript经典特效---cookie的写入.rar

    了解和熟练掌握JavaScript操作Cookie的方法对于前端开发至关重要,因为Cookie在用户跟踪、状态管理等方面发挥着重要作用。通过学习和实践,你可以更好地利用Cookie来提升用户体验,构建更智能的Web应用。

    javascript针对cookie的基本操作实例详解.docx

    然而,JavaScript本身并没有提供直接操作Cookie的方法,因此,掌握如何利用JavaScript来读取、写入和管理Cookie是非常必要的。 #### Cookie的基本概念 Cookie是由服务器端生成,并发送给User-Agent(通常是浏览器)...

    JavascriptCookie一个轻量级别的浏览器端cookie操作的库

    - **读取Cookie**:能够轻松获取指定名称的cookie的值,如果cookie不存在则返回`undefined`。 - **更新Cookie**:当需要修改已存在的cookie时,可以通过重新设置cookie来实现更新。 - **删除Cookie**:可以删除...

    Javascript Cookie读写删除操作的函数

    在本文中,我们将深入探讨如何使用JavaScript进行Cookie的读、写和删除操作。 首先,我们来看读取Cookie的函数`getCookie`: ```javascript function getCookie(name) { var start = document.cookie.indexOf...

Global site tag (gtag.js) - Google Analytics