简体   繁体   中英

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.

<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. I am using the product ID from the id attribute as the key for the saved 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. 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.

How can I get an array that has the keys for all current javascript cookies?

You can list cookies for current domain:

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

Answer posted by DixonD in How can I list all cookies for the current page with Javascript?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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