【问题标题】:how to read cookies in jquery?如何在 jquery 中读取 cookie?
【发布时间】:2019-10-16 12:52:38
【问题描述】:

我正在使用 carhartl 的 jQuery cookie 插件创建一个带有对象的键和值的 cookie,在我的一个方法中,我调用了 create cookie,然后我调用了 get cookie;但是 read 方法不起作用: makeCookie 方法:

function makeCookie(name,value){
    $.cookie(name,value);
}

readCookie 方法:

function readCookie(name){
    $.parseJSON($.cookie(name));
}

并调用这两个方法:

makeCookie('chatPopups',popUps);
    var all=readCookie('chatPopups');
    alert(all);

popUps 是一个全局 javascript 对象;

我得到的错误是:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

谁能帮帮我?

【问题讨论】:

  • 请在 readCookie 函数中使用 console.log($.cookie(name)) 并在此处列出其日志。所以这将有助于回答
  • 它记录了 [object Object],但我无法获取对象

标签: jquery cookies


【解决方案1】:

请在readCookie 函数中尝试此代码更改

readCookie 方法:

function readCookie(name){
    return $.cookie(name); // no parse needed because its not a json object of cookie
}

【讨论】:

  • 它返回未定义。
【解决方案2】:

您的 $.cookie() 方法看起来不错。

问题很可能在于弹出窗口,它可能不是格式良好的 JSON 字符串,因为 $.parseJSON() 非常敏感。

由于 popUps 是一个全局 JavaScript 对象,您可以只使用 return $.cookie(name); 而无需解析 JSON。

【讨论】:

    【解决方案3】:

    解决了问题,将makeCookie方法改成这样:

    function makeCookie(name,value){
        $.cookie(name,$.param(value),{ path: '/' });
    }
    

    和 readCookie 方法:

    function readCookie(name){
        var readCookie=$.cookie(name);
        readCookie = readCookie.split('&');
        if(readCookie.length != 0){
        for (i=0; i<readCookie.length; i++) {
            readCookie[i] = readCookie[i].split('=');
            popUps[readCookie[i][0]] = readCookie[i][1];
        }
        }
    }
    

    【讨论】:

      【解决方案4】:

      试试这个

      function getCookieValue(cname) { // cname is nothing but the cookie value which contains 
                                  // the value
                          var name = cname + "=";
                            var decodedCookie = decodeURIComponent(document.cookie);
                            var ca = decodedCookie.split(';');
                            for(var i = 0; i <ca.length; i++) {
                              var c = ca[i];
                              while (c.charAt(0) == ' ') {
                                c = c.substring(1);
                              }
                              if (c.indexOf(name) == 0) {
                                return c.substring(name.length, c.length);
                              }
                            }
                            return "";
                          }
      

      【讨论】:

      • 请为您的答案添加解释,而不仅仅是代码。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-10
      • 2015-11-25
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      相关资源
      最近更新 更多