读取从NewCookie()创建的cookie [英] Read cookie which is created from NewCookie()

查看:180
本文介绍了读取从NewCookie()创建的cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Newcookie()创建了一个cookie,我可以通过浏览器访问它,如下所示。现在我需要读取cookie

I created a cookie using Newcookie() and I can access it thorough the browser as below. Now I need to read the cookie

    function getCookieValue(cookieName) {
    console.log("=====getCookieValue=======");
    var name = cookieName + "=";
    var cookies = document.cookie.split(';');
    console.log("=====ALL cookies======="+cookies);
    if (!cookies) {
        return null;
    }
    console.log("=====cookies.length======="+cookies.length);
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        console.log("=====cookies======="+cookies[0]);
        if (cookie.indexOf(name) == 0) {
            return cookie.substring(name.length, cookie.length);
        }
    }
    return null;
}

但是通过使用这种方法我不能读取cookie。请给我建议。
感谢

But by using that method I cant read the cookie. Please advice me on this. Thanks

推荐答案

您的功能几乎完美。您只需要更改此行:

Your function is almost perfect. You just need to change this line:

document.cookie.split(';');

您可以通过运行上面的语句来检查控制台中的结果:所有cookie ,但每个都由空格前缀。这是为什么比较

You can examine the result in the console by running the above statement: you’ll get an Array with all the cookies but each one of them is preceeded by a whitespace. That’s why the comparison

if (cookie.indexOf(name) == 0)

无法像预期的那样工作,因为预期的子字符串不是从0开始而是从1开始。

doesn’t work like expected, because the expected substring doesn’t start at position 0 but at 1.

因此,您不希望使用单个分号而是使用分号和空格来分割Cookie列表。我不确定所有的浏览器,所以我认为最安全的方法是使用RegExp检查可选的空格:

Therefore, you’ll want to split the list of cookies not by a single semicolon but by a semicolon and a whitespace. I’m not sure about all the browsers out there, so I think the safest way to do it is with a RegExp that checks for an optional whitespace:

document.cookie.split(/;\s?/);

这篇关于读取从NewCookie()创建的cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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