【问题标题】:How can I get an array of the keys of all current javascript cookies?如何获取所有当前 javascript cookie 的键数组?
【发布时间】:2013-04-02 04:42:16
【问题描述】:

我有各种产品的链接。我正在使用 php 将数据库中的产品 ID 添加为每个链接的 id 值。

<a class="order_btn" id="<?php echo $row['product_id'];?>"><?php echo $row['product_name']; ?></a>

我正在使用 jquery cookie 插件(https://github.com/carhartl/jquery-cookie)来保存点击订单按钮的次数。我使用 id 属性中的产品 ID 作为已保存 cookie 的键。

$(".order_btn").click(function() {
  var productToAdd = $(this).attr("id");

  if($.cookie("Product-"+productToAdd) >= 1) { //If this is not the first item for the current product
    //Updating the number for the current product 
    var newNum = Number($.cookie("Product-"+productToAdd)) + 1;
    $.cookie("Product-"+productToAdd, newNum);
  } else { //If this the first item for the current product
    //Creating the first number for the current product
    $.cookie("Product-"+productToAdd, 1);
  }
}); //end click function for Order Button

在购物车页面上,我需要列出每个已保存值的 cookie 的产品名称。因此,我需要能够获取 cookie 的键名,以便在数据库中查找产品名称。

如何获得一个包含所有当前 javascript cookie 的键的数组?

【问题讨论】:

    标签: php javascript jquery cookies jquery-cookie


    【解决方案1】:

    您可以列出当前域的 cookie:

    function listCookies() {
        var theCookies = document.cookie.split(';');
        var aString = '';
        for (var i = 1 ; i <= theCookies.length; i++) {
            aString += i + ' ' + theCookies[i-1] + "\n";
        }
        return aString;
    }
    

    但出于安全原因,您不能列出其他域的 cookie

    DixonD 在How can I list all cookies for the current page with Javascript? 中发布的答案

    【讨论】:

    • 这是否适用于我使用 jquery cookie 插件设置的 cookie?
    • 我正在尝试将所有当前的 cookie 键保存在一个数组中。
    • 列出当前 document 的 cookie,而不是域。
    猜你喜欢
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多