cookie—基于js的coolie使用

Posted 老人与JAVA

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了cookie—基于js的coolie使用相关的知识,希望对你有一定的参考价值。

//设置cookie
function setCookie(name,value)
{
  var Days = 30;
  var exp  = new Date();
  exp.setTime(exp.getTime() + Days*24*60*60*1000);
  document.cookie = name + "="+ escape(value) +";expires="+ exp.toGMTString();
}

//获取cookie  1
function getCookie(name)
{
  var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
  if(arr != null) return unescape(arr[2]); return null;
}

//获取cookie   2
function getCookie(cname) {

    var name = cname + "=";
    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);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

//删除cookie
function delCookie(name)
{
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval=getCookie(name);
  if(cval!=null) document.cookie=name +"="+cval+";expires="+exp.toGMTString();
}

function goBuy(id, price)
 {
    var newCookie = "";
    var oldCookie = getCookie("product");
    if(oldCookie) {
        if(inArray(oldCookie.split(","), id)) {
            newCookie = oldCookie;
        } else {
            newCookie = id + "," + oldCookie;
        }
    } else {
        newCookie = id;
    }
    setCookie("product", newCookie);
    location.href = "shopping.html";
 }

function delShopping(id)
{
    comfire("");
    var tr = document.getElementById("product_id_"+ id);
    var oldCookie = getCookie("product");
    if(oldCookie) {
        var oldCookieArr = oldCookie.split(",");
        var newCookieArr = new Array();
        for(c in oldCookieArr) {
            var cookie = parseInt(oldCookieArr[c]);
            if(cookie != id) newCookieArr.push(cookie);
        }
        var newCookie = newCookieArr.join(",");
        setCookie("product", newCookie);
    }
    if(tr) tr.parentNode.removeChild(tr);
}

 

以上是关于cookie—基于js的coolie使用的主要内容,如果未能解决你的问题,请参考以下文章

js代码片段: utils/lcoalStorage/cookie

XSS:如何从 C# 中的字符串中删除 JS 片段?

Cookie的使用(基于js-cookie插件)

Backbone.js 状态管理/基于 url 片段的视图初始化

如何在 Reactjs 中添加丰富的代码片段?

python三大框架之一flask中cookie和session的相关操作