jquery将json数据对象保存在cookie中 [英] jquery save json data object in cookie

查看:74
本文介绍了jquery将json数据对象保存在cookie中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 JSON 数据保存在 cookie 中?

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());

并检索我想将其加载到 $("#ArticlesHolder") 中的数据,例如

and to retrieve the data i want to load it into $("#ArticlesHolder") like

$.each($.cookie("basket-data"), function(i,e){
 $("#ArticlesHolder").data(i, e);
});

有谁知道我是否在正确的轨道上,还是应该以其他方式完成?简单地说,我如何从 cookie 中放入和拉取 json 数据?

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 serialize 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屋!

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