Cookie adding another entry instead of replacing existing value

流过昼夜 提交于 2019-12-11 04:48:26

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/11565868/cookie-adding-another-entry-instead-of-replacing-existing-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!