如何检索 cookie 的值?
我可能问错了问题,但我对 JavaScript 还很陌生。我需要创建一个 cookie 来限制用户使用在线产品演示的次数。在伪代码中,我认为它会是这样的:
if(readCookie('demo') == null){
createCookie('demo','1',1);} //Assuming the functions for setting a cookie and retrieving it have already been created.
else {
readCookie('demo');
}
if demo cookie has value{
increment the value by one
}
else if value exceeds 10 {
alert message //I set this so I could test out the function
}
任何帮助将不胜感激!
I may be asking the wrong question but I am still fairly new to JavaScript. I need to create a cookie that will re-strict the number of usages a user has for an online product demo. In pseudo code, I assume it would be something like this:
if(readCookie('demo') == null){
createCookie('demo','1',1);} //Assuming the functions for setting a cookie and retrieving it have already been created.
else {
readCookie('demo');
}
if demo cookie has value{
increment the value by one
}
else if value exceeds 10 {
alert message //I set this so I could test out the function
}
Any help would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此页面将告诉您需要了解的所有内容,甚至提供示例函数供您插入自己的代码中,以使 cookie 处理变得非常容易。
http://www.quirksmode.org/js/cookies.html
This page will tell you everything you need to know and even provides example functions for you to plug into your own code to make cookie handling very easy.
http://www.quirksmode.org/js/cookies.html
如果您愿意使用 jQuery,您应该查看 jquery.cookie示例
(通过文档):
创建会话 cookie:
创建过期 cookie,7 天后:
创建过期 cookie,在整个页面有效:
读取 cookie:
通过传递 null 作为值来删除 cookie:
If your open to using jQuery, you should look at the jquery.cookie plugin.
Examples (via Documentation):
Create session cookie:
Create expiring cookie, 7 days from then:
Create expiring cookie, valid across entire page:
Read cookie:
Delete cookie by passing null as value:
正如用户评论所指出的,cookie 不是执行此操作的好方法。你无法强制执行它。
也就是说,我编写并维护了一个 JavaScript cookie API。请访问:http://code.google.com/p/cookies/ (它不需要 jQuery,尽管如果存在 jQ,它会内置额外的功能)。
这是翻译为使用该库的伪代码: http://jsfiddle.net/JAAulde/BGFQs/(点击“运行”足够多次后您将看到警报)
As noted by a user-comment, a cookie is not a good way to do this. You cannot enforce it.
That said, I wrote and maintain a JavaScript cookie API. Check it out at: http://code.google.com/p/cookies/ (It does NOT require jQuery, although it has extras built in if jQ is present).
Here is your pseudo code translated to use the lib: http://jsfiddle.net/JAAulde/BGFQs/ (You'll see the alert after clicking "Run" enough times)