jquery保存json在cookie中的数据对象 [英] jquery save json data object in cookie
问题描述
如何在Cookie中保存JSON数据?
How do I save JSON data in a cookie?
我的JSON数据如下所示
My JSON data looks like this
$("#ArticlesHolder").data('15', {name:'testname', nr:'4',price:'400'});
$("#ArticlesHolder").data('25', {name:'name2', nr:'1', price:'100'});
$("#ArticlesHolder").data('37', {name:'name3', nr:'14', price:'60'});
我想做
var dataStore = $.cookie("basket-data", $("#ArticlesHolder").data());
并检索要加载到 $(#
and to retrieve the data i want to load it into $("#ArticlesHolder")
like
$.each($.cookie("basket-data"), function(i,e){
$("#ArticlesHolder").data(i, e);
});
有没有人知道我是否在正确的轨道上,还是应该以其他方式完成?
does anyone know if I'm on the right track or should this be done in some other way? Simply put, how do i put and pull json data from a cookie?
推荐答案
您可以将数据串行化为JSON,像这样:
You can seriaize the data as JSON, like this:
$.cookie("basket-data", JSON.stringify($("#ArticlesHolder").data()));
然后从cookie中获取:
Then to get it from the cookie:
$("#ArticlesHolder").data(JSON.parse($.cookie("basket-data")));
这依赖于 JSON.stringify()
和 JSON.parse()
序列化/反序列化数据对象,对于旧版浏览器(IE <8)包括 json2.js 以获取 JSON
功能。此示例使用 jQuery Cookie插件
This relies on JSON.stringify()
and JSON.parse()
to serialize/deserialize your data object, for older browsers (IE<8) include json2.js to get the JSON
functionality. This example uses the jQuery cookie plugin
这篇关于jquery保存json在cookie中的数据对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!