如何获取 Cookie 中的值

本文关键字:Cookie 获取 何获取 | 更新日期: 2023-09-27 18:35:15

我有以下代码

var s = Request.Cookies["myvalue"].Value;
string[] values = s.Split(',').Select(x => x.Trim()).ToArray();

这是 Jquery

$(document).ready(function () {
    $("#btnAddToCart").click(function () {
        $(this).css("background-color", "green");
        if (typeof $.cookie('myvalue') == 'undefined') {
            $.cookie("myvalue", 0, { expiry: 1 });
        }            
        var a = $(".img1").attr("id");          
        var imgsrc = $.cookie("myvalue").split(",");
        var count = 0;
        var totalitems = 0;
        for (var i = 0; i < imgsrc.length; i++) {                             
            if (a == imgsrc[i]) {
                break;
            }
            else {
                count++;
            }
        }
        var lenghtOfArry = imgsrc.length;
        if (count >= lenghtOfArry) {
            $.cookie("myvalue", $.cookie("myvalue") + "," + a, { expiry: 10 });
        }
        else {
            alert('This value already exist');
        }
        for (var i = 0; i < imgsrc.length; i++) {
            totalitems++;
        }
        $(".para").text("CART" + " " + "(" + totalitems + ")");
        $(".para").css("color", "#fff");
        $(".para").css("text-align", "center");
    });
});

当我尝试在调试时访问 cookie 值时,它给出的值为

0%2C40%2C50%2C60%2C80%2C9

我希望这些值为

0 4 5 6 8 9

怎么办?

如何获取 Cookie 中的值

您的 cookie 值似乎是 url 编码的。请尝试以下操作:

var s = Request.Cookies["myvalue"].Value;
s = HttpUtility.UrlDecode(s ?? string.Empty);
string[] values = s.Split(',').Select(x => x.Trim()).ToArray();