我正在使用 jquery 开发客户端 Web 应用程序
我想存储所有访问过的页面,为此我使用cookie
所以,我有两个元素要存储:
- 页面网址
- 页面标题
我开始在 cookie 中创建数据:
Index.html :
if(!$.cookie("history")){
var url_history = document.location;
var title_history = $("html title").text();
$.cookie("historyURL", url_history);
$.cookie("historyTITLE", title_history);
}
另一个页面.html :
var url_history = document.location;
var title_history = $("html title").text();
$.cookie("historyURL", url_history);
$.cookie("historyTITLE", title_history);
问题是 cookie 的新值覆盖了旧值。
我想我应该设置一个对象,而不是字符串,例如:
var objHistory = [];
objHistory.push({url:document.location, title: $("html title").text()})
$.cookie("history", objHistory);
现在我有另一个问题:
我无法从 cookie 中检索我的对象
当我试图从 cookie 中获取我的对象时,它显示的是字符串“object”而不是 Object
是否可以在cookie中设置一个对象?
谢谢你的帮助
最佳答案
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));
关于javascript - 将对象设置为 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13290275/