饼干中添加一个条目而不是替换现有值 [英] Cookie adding another entry instead of replacing existing value

查看:71
本文介绍了饼干中添加一个条目而不是替换现有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用流行的jQuery插件的cookie设置会话cookie的值通过JavaScript像这样:

 函数ChangeLoginUser(SEL){
    VAR selectedUser = sel.options [sel.selectedIndex] .value的;
    $ .cookie(LoginUser,selectedUser);
    location.reload(真); //刷新
}

用户从网站全球下拉框选项选择后,此函数被调用。


  • 在第1页更改值 - Cookie设置CookieName =值。

  • 转到第2页 - 该Cookie坚持正确

  • 更改下拉值值2 - 提琴手现在显示两个cookie同名像这样两个值:


  CookieName = VALUE2
CookieName =值


我不明白为什么会这样。我需要保持只有一个这个名字的cookie。新的值应该取代旧的。


解决方案

确定。它看起来像问题是与Cookie路径。每个URL可以有相同名称的单独的cookie。解决的办法是设置的路径是域范围内是这样的:

  $饼干(LoginUser,selectedUser,{路径:'/'});

或者,如果你需要将它缩小到只有您的应用程序,你可以做这样的:

  $饼干(LoginUser,selectedUser,{路径:APPPATH});

在这里APPPATH可以在共享的布局开始时设置

 <脚本类型=文/ JavaScript的>
    VAR APPPATH ='@ Url.Content(〜/)'
< / SCRIPT>

I am using the popular jquery cookie plugin to set a session cookie value via javascript like so:

function ChangeLoginUser(sel) {
    var selectedUser = sel.options[sel.selectedIndex].value;
    $.cookie("LoginUser", selectedUser);
    location.reload(true); //refresh
}

This function is called after user selects from a site global drop-down box option.

  • Change the value on page1 - the cookie is set CookieName = Value1.
  • Go to page2 - The cookie is persisting correctly
  • Change the drop-down value to value2 - Fiddler now shows two cookies by the same name with both values like this:

CookieName = value2
CookieName = value1

I don't understand why this is happening. I need to keep only one cookie of this name. The new value is supposed to replace the old one.

解决方案

Ok. It looks like the problem was with the cookie path. Each URL can have a separate cookie with the same name. The solution is to set the path to be domain wide like this:

$.cookie("LoginUser", selectedUser, { path: '/' });

or, if you need to narrow it down to only your application you can do it like this:

$.cookie("LoginUser", selectedUser, { path: AppPath });

where AppPath can be set in the beginning of your shared layout

<script type="text/javascript">
    var AppPath = '@Url.Content("~/")'
</script>

这篇关于饼干中添加一个条目而不是替换现有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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