[英]How to properly store an array of objects in a cookie using json.stringify?
我正在尝试使用JSON.Stringify在cookie中存储对象数组,但是当我解析cookie并尝试将新对象推入数组然后再次对其进行字符串化时遇到了问题。 它告诉我comments.push不是函数。
var comments = []; var myData = 0; function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+d.toUTCString(); document.cookie = cname + "=" + cvalue + "; " + expires; } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) == 0) return c.substring(name.length, c.length); } return ""; } function checkCookie() { var commentAux = getCookie("myComments"); if (commentAux != "") { //alert("Welcome again " + user); return true; } else { return false; } } function validateComment() { var x = document.forms["commentForm"]["commentSection"].value; if (x == null || x == "") { alert("There's nothing to comment, write something to proceed."); return false; } else { var comment = { firstName:"Name", lastName:"Surname", text:x }; if (checkCookie() == false) { setCookie("myComments", JSON.stringify(comment), 1); } else { myData = getCookie("myComments"); comments = JSON.parse(myData); alert(comments); comments.push(comment); setCookie("myComments", JSON.stringify(comments), 1); } } alert(comments.length); }
<!DOCTYPE html> <html> <head> <title>Facebook Simulator by Azael Alanis</title> <link rel="stylesheet" type="text/css" href="style.css"> <script src="javascript.js"></script> </head> <body> <img src="facebook-banner.png" alt="Facebook-Banner" style="height:100px;width:800px"> <div id="section"> <form name="commentForm" onsubmit="validateComment()"> <input type="text" name="commentSection" placeholder="What's on your mind?"><button class="buttonText">Enviar</button> </form> </div> </body> </html>
可能是什么问题呢? 我只想解析我的cookie->将新对象添加到数组->再对其进行字符串化
谢谢
这是你的问题:
comments = JSON.parse(myData);
comments.push(comment);
你可能想做
var comment = JSON.parse(myData);
comments.push(comment);
由于JSON.parse(myData)
返回一个注释对象。
您使用以下代码:
var comment = { /* ... */ };
if (checkCookie() == false) {
setCookie("myComments", JSON.stringify(comment), 1);
} else {
comments = JSON.parse(getCookie("myComments"));
comments.push(comment);
setCookie("myComments", JSON.stringify(comments), 1);
}
问题在于,最初存储对象comment
而不是包含对象comment
的数组。
因此,下一次,当您尝试发送其他comment
,您将无法执行。
请尝试以下操作:
var comment = { /* ... */ };
if (checkCookie() == false) {
setCookie("myComments", JSON.stringify([comment]), 1); // <-- array
} else {
comments = JSON.parse(getCookie("myComments"));
comments.push(comment);
setCookie("myComments", JSON.stringify(comments), 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.