简体   繁体   English

如何获取当前所有JavaScript cookie的键数组?

[英]How can I get an array of the keys of all current javascript cookies?

I have links for various products. 我有各种产品的链接。 I am using php to add the product ID from the database as the id value for each link. 我正在使用php从数据库添加产品ID作为每个链接的ID值。

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

I am using the jquery cookie plugin( https://github.com/carhartl/jquery-cookie ) to save the number of times the order button is clicked. 我正在使用jquery cookie插件( https://github.com/carhartl/jquery-cookie )来保存单击订单按钮的次数。 I am using the product ID from the id attribute as the key for the saved 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

On the Cart page, I need to list out the Product Name for each cookie that has saved values. 在“购物车”页面上,我需要列出每个已保存值的Cookie的产品名称。 Therefore, I need to be able to get the name of the key for the cookie so I can look up the products name in the database. 因此,我需要能够获取cookie的密钥名称,以便可以在数据库中查找产品名称。

How can I get an array that has the keys for all current javascript cookies? 如何获得具有所有当前javascript cookie键的数组?

You can list cookies for current domain: 您可以列出当前域的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;
}

But you cannot list cookies for other domains for security reasons 但是出于安全原因,您无法列出其他域的Cookie

Answer posted by DixonD in How can I list all cookies for the current page with Javascript? DixonD在“ 如何使用Java脚本列出当前页面的所有cookie”中发布的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM