我有以下内容:
var cookie = $.cookie("Test_cookie");
var items = cookie ? eval("([" + cookie + "])") : [];
var jsonObj = { packageId: "11", machineId: "1", operationType: "Download" };
items.push(jsonObj);
$.cookie(cookieName, JSON.stringify(items), { expires: 1, path: '/' });
结果:
[{"packageId":"11","machineId":"1","operationType":"Download"}]
这是正确的。
然而,当我第二次运行它时,我想将新对象追加到项目中,但是json搞砸了(注意额外的“[”):
var jsonObj = { packageId: "11", machineId: "1", operationType: "Download" };
items.push(jsonObj);
$.cookie(cookieName, JSON.stringify(items), { expires: 1, path: '/' });
结果:
[[{"packageId":"11","machineId":"1","operationType":"Download"}],{"packageId":"11","machineId":"1","operationType":"Download"}]
应该是:
[{"packageId":"11","machineId":"1","operationType":"Download"},{"packageId":"11","machineId":"1","operationType":"Download"}]
是什么给了什么?
答案 0 :(得分:3)
你的错误就在附近
var items = cookie ? eval("([" + cookie + "])") : [];
只做
var items = cookie ? eval(cookie) : [];