如何更新和删除Cookie? [英] How to update and delete a cookie?

查看:192
本文介绍了如何更新和删除Cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助来了解如何更新值以及如何删除从此代码创建的 cookie !我是JavaScript的新手,所以如果有人可以帮助我,真是太好了。

I need help to know how to update values and how to delete a cookie created from this code! I'm new to JavaScript so it's great if anyone can help me.

function getCookie(c_name) {
     var i,x,y,ARRcookies = document.cookie.split(";");
     for (i=0;i<ARRcookies.length;i++) {
          x = ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
          y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
          x = x.replace(/^\s+|\s+$/g,"");
          if (x==c_name) {
              return unescape(y);
          }
      }
}

function setCookie(c_name,value,exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays==null) ? "" : ";                                    expires="+exdate.toUTCString());
   document.cookie=c_name + "=" + c_value;
 }

function check2Cookie() {
     var username=getCookie("username");
     if (username!=null && username!="") {
         username= "0";
         setCookie("username",username,1000);
     }
     else {
         username=" ";
         if (username!=null && username!="") {
               username= "0";
               setCookie("username",username,1000);
         }
     }
}

这是cookie的代码

This is the code for cookie creation.

创建代码为 setCookie( username,username,1000);

现在如何更新此cookie并删除此cookie。

Now how to update this cookie and delete this cookie.

推荐答案

http://www.quirksmode.org/js/cookies.html

更新将使用createCookie重置

update would just be resetting it using createCookie

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        var expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length,c.length);
        }
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

这篇关于如何更新和删除Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆