簡體   English   中英

檢索 jQuery Cookie 值

[英]Retrieve jQuery Cookie value

例如,我有這個 cookie:

$.cookie("foo", "500", { path: '/', expires: 365 });

如何獲取該 cookie 的值並將其放入變量中?

例如(我知道這是不正確的):

var foo = $.cookie("foo").val();

這只是var foo = $.cookie("foo")

不需要.val()調用,因為您沒有訪問 DOM 元素的

通過這種方式我們可以訪問

console.log($.cookie()); //它將以object的形式給出所有cookies

alert($.cookie('foo')); //它將給cookie foo值即500

要獲取 cookie 的值,您只需調用它的引用即可。 例如:

$.cookie("foo", "somevalue");
alert($.cookie("foo"));

會提醒:

somevalue

這對我有用

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 "";
                    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM