[英]Get a cookie's single value javascript
I already have a script that check for the cookies existence, but i need it to get the cookies value so i can use it in a url like this: 我已经有一个检查cookie存在的脚本,但我需要它来获取cookie值,所以我可以在这样的URL中使用它:
var lang = cookievalue;
location.replace(window.location.protocol+"//"+document.domain+"/"+cookievalue+window.location.pathname);
so what would be the easiest way to simply get the value of a cookie through javascript, everything i've looked for seems to involve spliting the value and stuff,w hich is not necesary since theres simply only one value (en,fr,es etc) 那么通过javascript简单地获取cookie的最简单的方法是什么,我所寻找的所有东西似乎都涉及分割价值和东西,因为它只是一个值(en,fr,es)等等)
function getCookieValue(key) {
var cookies = document.cookie.split('; ');
for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) {
if (decode(parts.shift()) === key) {
return decode(parts.join('='));
}
}
return null;
}
function decode(s) {
return decodeURIComponent(s.replace(/\+/g, ' '));
}
Then, to get a value for a cookie named my_cookie_name
, you would use getCookieValue('my_cookie_name')
. 然后,要获取名为
my_cookie_name
的cookie的值,您将使用getCookieValue('my_cookie_name')
。
Also as an alternative , you can use the jquery-cookie
plugin. 此外,作为替代方案 ,你可以使用
jquery-cookie
插件。 It's very simple to use ( $.cookie('my_cookie_name')
) and lightweight. 它的使用非常简单(
$.cookie('my_cookie_name')
)和轻量级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.