将对象设置为 cookie

Val*_*ane 4 html javascript cookies web

我正在使用 jquery 开发客户端 Web 应用程序

我想存储所有访问过的页面,我为此使用了 cookie

所以,我有两个元素要存储:

  • 网页网址
  • 页面标题

我开始在 cookie 中创建数据:

索引.html:

if(!$.cookie("history")){
        var url_history = document.location;
        var title_history = $("html title").text();
        $.cookie("historyURL", url_history);
        $.cookie("historyTITLE", title_history);
    }
Run Code Online (Sandbox Code Playgroud)

anotherPage.html :

var url_history = document.location;
var title_history = $("html title").text();
$.cookie("historyURL", url_history);
$.cookie("historyTITLE", title_history);
Run Code Online (Sandbox Code Playgroud)

问题是 cookie 的新值会覆盖旧值。

我想我应该设置一个对象,而不是字符串,例如:

var objHistory = [];
objHistory.push({url:document.location, title: $("html title").text()})
$.cookie("history", objHistory);
Run Code Online (Sandbox Code Playgroud)

现在我有另一个问题:

我无法从 cookie 中检索我的对象

当我试图从 cookie 中获取我的对象时,它显示一个字符串“对象”而不是对象

是否可以在 cookie 中设置对象?

感谢您的帮助

sai*_*iuc 6

cookie(具有有限的 4K 大小)是我尝试存储访问过的页面数组的最后一个地方。由于其局限性,cookie 将是我尝试使用的最后一种存储方法。如果您使用 HTML5,为什么不为此目的使用 localStorage?

教程:http : //www.w3schools.com/html/html5_webstorage.asp

localStorage 仅处理 STRING 键/值对。一种解决方法是在存储对象之前将其字符串化,然后在检索它时对其进行解析:

var testObject = { 'URL': 1, 'TITLE': 2 };
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
Run Code Online (Sandbox Code Playgroud)


Alb*_*aro 5

您始终可以将对象字符串化为 JSON:

var jsonHistory = JSON.stringify(objHistory);
$.cookie("history", jsonHistory);
Run Code Online (Sandbox Code Playgroud)

编辑

简单演示(在 Chrome 和 Firefox 中测试):

        (function(){
            var o = JSON.parse('{"id":1,"value":"code.google.com"}');
            var e = 'Thu Nov 10 2012 15:44:38';
            document.cookie = 'myObj='+ JSON.stringify(o) +';expires=' + e;
        })()
Run Code Online (Sandbox Code Playgroud)