为什么jQuery cookie实际上没有设置cookie?

dan*_*007 11 javascript jquery json jquery-cookie

我正在使用使用cookie的jQuery开发一个应用程序.现在,它位于application.html我的PC桌面上.

但是,我无法存储和检索cookie.我按顺序包含了jquery-1.7.1.min.js,json2.js并且jquery.cookie.js在我的HTML文件中.

这是我如何存储cookie持续7天:

$.cookie("people", JSON.stringify(people_obj_array), {expires: 7});
Run Code Online (Sandbox Code Playgroud)

全局数组people_obj_array看起来像

[
        {
            "name": "Adam",
            "age": 1,
        },
        {
            "name": "Bob",
            "age": 2,
        },
        {
            "name": "Cathy",
            "age": 3,
        },
    ]
Run Code Online (Sandbox Code Playgroud)

当我测试JSON加密时alert(JSON.stringify(people_obj_array)),它看起来很好:

JSON测试

但是,当我通过以下方式检索此cookie时:

alert($.cookie("people"));
Run Code Online (Sandbox Code Playgroud)

甚至在刷新页面之前,会弹出一个"null"的警告.文本不应该是警告JSON字符串吗?我正确使用JQuery cookie库吗?


只是为了澄清,这是我测试的方式:

$.cookie("people", JSON.stringify(people_obj_array), {expires: 7}); // store
alert($.cookie("people")); // attempt to retrieve
Run Code Online (Sandbox Code Playgroud)

我有Firebug,我愿意做一些控制台测试.

Dav*_*tts 11

这可能是因为桌面上的文件导致了问题.浏览器通常通过根据收到的域及其路径提供cookie来表现.

您可能无法在设置后立即读取cookie:编写cookie涉及在HTTP请求中设置标头,同样,读取它们涉及读取HTTP响应中的标头.

尝试在Web服务器上托管您的页面,看看它是否适合您.