Javascript 检索 jQuery Cookie 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6171865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve jQuery Cookie value
提问by daryl
Example, I have this cookie:
例如,我有这个 cookie:
$.cookie("foo", "500", { path: '/', expires: 365 });
How do I get the value of that cookie and put it into a variable?
如何获取该 cookie 的值并将其放入变量中?
For example (I know this is not correct):
例如(我知道这是不正确的):
var foo = $.cookie("foo").val();
回答by Matt Ball
It's just var foo = $.cookie("foo")
.
这只是var foo = $.cookie("foo")
。
There's no need for a .val()
call as you're not accessing the valueof a DOM element.
不需要.val()
调用,因为您没有访问DOM 元素的值。
回答by Sean Powell
To get the value of a cookie, you can just call it's reference. For example:
要获取 cookie 的值,您只需调用它的引用即可。例如:
$.cookie("foo", "somevalue");
alert($.cookie("foo"));
Will alert:
会提醒:
somevalue
回答by Lead Developer
By this way we can access
通过这种方式我们可以访问
console.log($.cookie());
//It will gives the all cookies in the form of object
console.log($.cookie());
//它将以对象的形式给出所有的cookies
alert($.cookie('foo'));
//it will give cookie foo value ie 500
alert($.cookie('foo'));
//它会给cookie foo值即 500
回答by Ankit Singh
This worked for me
这对我有用
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 "";
}