简体   繁体   English

读取cookie返回未定义

[英]Read cookies returns undefined

Here is my situation. 这是我的情况。 I have a dropdown to select country on home. 我有一个下拉菜单可以选择国内的国家。

If there is no cookie I set cookie default to "US", Then user open a link in new tab and goes to checkout page, I filter other countries and show only that selected country on dropdown select, everything is fine but when on first tab it changes country to DE on second tab Cookie is DE but the country is still US. 如果没有cookie,则将cookie的默认值设置为“ US”,然后用户在新标签页中打开一个链接,然后转到结帐页面,我过滤其他国家/地区,并在下拉菜单中仅显示所选国家/地区,但一切正常,但是在第一个标签页上时它在第二个标签上将国家/地区更改为DE。Cookie是DE,但国家/地区仍然是美国。

There are two options, 有两种选择,

<select id="country">
    <option>Select Country</option>
    <option value="US">Select Country</option>
</select>

What I want to do is 我想做的是

function readCookie(k){return(document.cookie.match('(^|; )'+k+'=([^;]*)')||0)[2]}  

or any other function to read cookies like some described here What is the shortest function for reading a cookie by name in JavaScript? 或任何其他读取Cookie 的功能(如此处所述),在JavaScript中按名称读取Cookie的最短功能是什么?

document.getElementById('country').onchange = function () { 
    this.options.length = 0;
    this.options[1] = new Option(readCookie('country'),readCookie('country'));
    this.options[1].setAttribute("selected","selected");
}

They return undefined but cookie is there when I inspect with profile. 它们返回未定义的值,但当我通过配置文件进行检查时仍存在cookie。 Basically, I just want to renew option based on cookie 基本上,我只想基于Cookie续订选项

when I do 当我做

document.getElementById('country').onchange = function () { 

    alert(readCookie('country'); //returns undefined
}

did you check the path when creating a cookie ? 创建cookie时是否检查了路径? make sure the path is /, i sometimes forget and create 2 cookies or cannot remove the old one. 确保路径为/,有时我会忘记创建2个cookie,或者无法删除旧的cookie。

我改为使用本地存储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM