如何使用jQuery读取Cookie并将其存储在变量中? [英] How can I use jQuery to read a cookie and store it in a variable?

查看:493
本文介绍了如何使用jQuery读取Cookie并将其存储在变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取"bar" cookie的内容并将其存储在变量"foo"中

I'd like to read the contents of the "bar" cookie and store it in variable "foo"

我的第一个刺是这个,但我没有收到警报.我认为分配声明不正确.

My first stab was this, but I'm not getting an alert. I think the assignment statement just isnt correct.

var foo = $.cookie('bar');
alert (foo);

推荐答案

如果您希望jQuery处理cookie操作,则需要使用库.

The use of a library is required if you wish to have jQuery handle the cookie manipulation.

https://github.com/carhartl/jquery-cookie

当您可以在简单的javascript中如此轻松地使用库时,有些人会皱眉.我个人一直在上面使用该库.

Some people frown on using a library when you can do it so easily in straight-up javascript.. Personally, i've always used the library above.

但是,如果您希望探索非jQuery方式...

However, If you wish to explore the non-jQuery way...

Google搜索提供了以下页面: http://www.tutorialspoint.com/javascript/javascript_cookies. htm

Google search provided this page: http://www.tutorialspoint.com/javascript/javascript_cookies.htm

我从来没有使用过直接的js来操作cookie,所以为了方便操作,我将从该站点复制/粘贴..您可以参考本段上方的链接以获取详细信息.

I've never used straight-up js to manipulate cookies, so i'll just copy/paste from that site for OPs ease.. You can reference the link just above this paragraph for specifics..

document.cookie = "key1=value1;key2=value2;expires=date";
function WriteCookie()
{
   var cookievalue= "ABCD";
   document.cookie="name=" + cookievalue;
   alert("Setting Cookies : " + "name=" + cookievalue );
}

阅读所有Cookie

function ReadCookie()
{
   var allcookies = document.cookie;
   alert("All Cookies : " + allcookies );

   // Get all the cookies pairs in an array
   cookiearray  = allcookies.split(';');

   // Now take key value pair out of this array
   for(var i=0; i<cookiearray.length; i++){
      name = cookiearray[i].split('=')[0];
      value = cookiearray[i].split('=')[1];
      alert("Key is : " + name + " and Value is : " + value);
   }
}

这篇关于如何使用jQuery读取Cookie并将其存储在变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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