获取Cookie的单一值javascript [英] Get a cookie's single value javascript

查看:72
本文介绍了获取Cookie的单一值javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有一个脚本来检查cookie的存在,
,但是我需要它来获取cookie的值,以便可以在这样的URL中使用它:

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:

var lang = cookievalue;
location.replace(window.location.protocol+"//"+document.domain+"/"+cookievalue+window.location.pathname);

那么什么是最简单的方法来简单地通过javascript获取cookie的值, ve寻找的似乎涉及将值和内容进行拆分,由于只存在一个值(en,fr,es等),因此不需要,因为

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)

推荐答案

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, ' '));
}

然后,获取名为的cookie的值my_cookie_name ,则可以使用 getCookieValue('my_cookie_name')

Then, to get a value for a cookie named my_cookie_name, you would use getCookieValue('my_cookie_name').

替代,您可以使用 jquery-cookie 插件。使用起来非常简单( $。cookie(’my_cookie_name'))并且轻巧。

Also as an alternative, you can use the jquery-cookie plugin. It's very simple to use ($.cookie('my_cookie_name')) and lightweight.

这篇关于获取Cookie的单一值javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆