【问题标题】:How to make an empty cookie check如何进行空 cookie 检查
【发布时间】:2021-12-01 00:57:39
【问题描述】:

我有一个购物车助手:

let cartHelper = {
    cartCookieName: "_cart",

    getCart: function (callback = undefined) {
        return apiHelper.getRequest(
            "/carts",
            (response) => {
                document.cookie = `${this.cartCookieName}=${response.data.attributes.cart_guid};`;
                if (callback) { callback(); }
            },
        )
    },
}

如果“_cart”为空,我想调用 getCart 函数。你能帮我做这个检查吗?更清楚的是,单击按钮时会调用 getCart 函数。我正在调用 API 来获取 cart_guid,并将其存储在 cookie 中。如果 cart_guid 已经在 cookie 中,我想做什么,我不想做任何事情,但如果不是,我想用 cartguid 创建 cookie。

感谢您的帮助。

【问题讨论】:

    标签: javascript cookies document setcookie


    【解决方案1】:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    
        <title>Document</title>
        <style></style>
      </head>
      <body>
        <button onclick="checkCookie()">Check Cookie</button>
        <p>Click btn to check cookie..!</p>
      </body>
      <script>
        function getCookie(name) {
          var dc = document.cookie;
          var prefix = name + "=";
          var begin = dc.indexOf("; " + prefix);
          if (begin == -1) {
            begin = dc.indexOf(prefix);
            if (begin != 0) return null;
          } else {
            begin += 2;
            var end = document.cookie.indexOf(";", begin);
            if (end == -1) {
              end = dc.length;
            }
          }
          // because unescape has been deprecated, replaced with decodeURI
          //return unescape(dc.substring(begin + prefix.length, end));
          return decodeURI(dc.substring(begin + prefix.length, end));
        }
    
        function checkCookie() {
          var myCookie = getCookie("MyCookie");
    
          if (myCookie == null) {
            console.log(
              "%ccookie is null",
              "color:white;background: red;padding: 2px 10px;"
            );
          } else {
            console.log(
              "%ccookie is not null",
              "color:white;background: red;padding: 2px 10px;"
            );
          }
        }
      </script>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-18
      • 2012-03-05
      • 1970-01-01
      • 2019-11-16
      • 2020-12-14
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多