Use cookie to save value temporarily

Time:2020-9-27

Product details:

//Cookie zero time storage cart
function addcar() {
  //Determine whether the cookie has a value
  if (getCookie("shopcar") == null) {
  //Array type
  setCookie("shopcar", "[]");
  }// in this example, the value is written dead
  var obj = {
    Name: "shoes", 
    Price: "1200"
  };

  //Gets the value, in this case of string type
  var liststr = getCookie('shopcar');
  //Type conversion
  var list = JSON.parse(liststr);
  //Additional value
  list.push(obj);
  //Save to cookie
  setCookie("shopcar", JSON.stringify(list));
  location.href = "/Default/ShopCar";
}

 

 

Shopping Cart:

//Cookie loading cart
function load() {
  //Gets the value, in this case of string type
  var liststr = getCookie("shopcar");
  //Type conversion
  var list = JSON.parse(liststr);
  $("#tb").empty();
  $(list).each(function () {
  $("#tb").append(
      '' +
      '' + this.Name + '' +
      '' + this.Price + '' +
      ''
    )
  })
}
load();

 

JavaScript:

/**
*Save value in cookie
* */
function setCookie(name, value) {
  if (value) {
    Var days = 1; // define a day
    var exp = new Date();
    exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
    //Write a cookie and togmstring to convert the time to a string
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString;
  }
};
/**
*Value in cookie
* */
function getCookie(name) {
   Var arr, reg = new regexp ("(^|) + name +" = ([^;] *) (; | $) "); // matching fields
   if (arr = document.cookie.match(reg)) {
     return unescape(arr[2]);
   }    else {
     return null;
   }
};

 

Recommended Today

Methods that may be used in regular expressions

This article mainly explains the methods used by regularization First of all, let’s start with a random string: let content = ‘gabgAjklbgadlkjgbajkdgbAjldgbadg’ The first is a simple method that doesn’t require regularization indexOf If you use a simple match STR or intercept the matched text, I will use the str.indexOf (SearchValue, [fromindex]), the index of […]